如何从元素中删除 angular 表达式属性

How to remove angular expression attributes from element

我想知道是否可以动态删除 Angular 表达式。 我尝试了以下但没有成功:

我的按钮

<button myDirective [disabled]="someExpression">Clippy</button>

我的指令

@Directive({
   selector: '[myDirective]'
})
export class MyDirective {
   constructor(private element: ElementRef) {}

   ngOnInit() {
      this.element.nativeElement.removeAttribute('disabled');
   }
}

问题

最初按钮不会被禁用,但是一旦 someExpression 重新评估它就会将禁用属性添加回元素。

为了澄清起见,我想动态删除一个 Angular 表达式。在上面的示例中,它是 [disabled]。但这在未来可以是任何约束。我希望我的指令否决现有绑定。

<button myDirective [disabled]="hideAttr">Clippy - {{hideAttr}}</button>

当 hideAttr 为 false 时,disabled 属性不会被移除

https://plnkr.co/edit/h86IUsny6MiLfRI9tsPx

您可能需要两个按钮副本,但一次只显示其中一个

<ng-container *ngIf="showButtonWithDisabledExpr">
        <button [disabled]="someExpression">Clippy</button>
</ng-container>

<ng-container *ngIf="!showButtonWithDisabledExpr">
        <button>Clippy</button>
</ng-container>

作为解决方法,您可以试试这个:

@Directive({
  selector: '[myDirective]'
})
export class MyDirective {
  @Input() disabled;

  constructor(private element: ElementRef) { }

  ngOnChanges() {
    if (this.disabled) {
      this.element.nativeElement.removeAttribute('disabled');
    }
  }
}

Stackblitz Example

使用@HostBinding,例如

import { Directive, HostBinding } from '@angular/core';

@Directive({
  selector: '[statusDirective]',
})
export class StatusDirective {
  @HostBinding('disabled') disable = true;
  constructor() {}
}

//Your input never enabled
//<input type="text" name="id" [disabled]="false" statusDirective  >

在较新的 Angular 版本中,您需要确保表达式的计算结果为空或未定义:

When the expression resolves to null or undefined, Angular removes the attribute altogether.

参见Attribute Binding

例如:

<button [disabled]="someExpression ? '' : null">Clippy</button>