【问题标题】:How to remove angular expression attributes from element如何从元素中删除角度表达式属性
【发布时间】:2017-12-06 12:49:46
【问题描述】:

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

我的按钮

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

我的指令

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

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

问题

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

为了澄清,我想动态删除一个 Angular 表达式。在上面的例子中它是[disabled]。但这在未来可能具有任何约束力。我希望我的指令推翻现有的绑定。

【问题讨论】:

  • 您可以通过将@Input 属性设置为自定义directive 来实现这一点并实现这一点
  • 您不需要指令来删除 [disable](不适用于 removeAttribute)“someExpression”可以是组件中的布尔变量
  • @Eliseo 不,禁用只是一个例子。我希望我的指令推翻在这种情况下禁用的属性

标签: angular angular-directive


【解决方案1】:

您可以尝试以下解决方法:

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

  constructor(private element: ElementRef) { }

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

Stackblitz Example

【讨论】:

    【解决方案2】:

    使用@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  >
    

    【讨论】:

    • 这在表达式改变之前有效,我想我必须使用@yurzui 发布的ngOnChanges
    【解决方案3】:
    <button myDirective [disabled]="hideAttr">Clippy - {{hideAttr}}</button>
    

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

    https://plnkr.co/edit/h86IUsny6MiLfRI9tsPx

    【讨论】:

    • 我知道,这不是我想要的。我想删除整个绑定
    • @Dieterg 好的,谢谢
    • 你可以使用@hostBinding
    【解决方案4】:

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

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

    【讨论】:

      【解决方案5】:

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

      当表达式解析为 null 或 undefined 时,Angular 会完全删除该属性。

      Attribute Binding

      所以一个例子是:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-18
        • 2015-03-13
        • 1970-01-01
        • 1970-01-01
        • 2016-01-22
        • 1970-01-01
        相关资源
        最近更新 更多