如何从元素

时间:2017-12-06 12:49:46

标签: angular angular-directive

我想知道是否可以动态删除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]。但这可能是未来的任何约束力。我希望我的指令能够否决现有的绑定。

4 个答案:

答案 0 :(得分:3)

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

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

  constructor(private element: ElementRef) { }

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

<强> Stackblitz Example

答案 1 :(得分:1)

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

答案 2 :(得分:0)

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

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

https://plnkr.co/edit/h86IUsny6MiLfRI9tsPx

答案 3 :(得分:0)

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

 $.ajax({
        type: "GET",
        dataType: "JSON",
        url: "http://localhost:8080/xxx.php/",
        success: function (msg, result, status, xhr) {
            var obj= msg.data;
           if(msg.data.length){       
                  alert(msg.data[0].name);// wll give name at 0 index
              }
        },
        error: function (error) {
        }
    });
相关问题