Angular 2有条件地添加属性指令

新手上路,请多包涵

我在这里看到两个问题如何有条件地添加和删除项目的属性( 是否可以使用 Angular2 有条件地显示元素属性? )但我的问题是是否可以添加和删除 属性指令?我能够添加和删除属性,但 Angular 不会将该属性“编译”为属性指令,而是该属性只是坐在那里什么也不做。这是 2 个标签的示例:

第一个是我试图有条件地应用属性指令的那个,第二个一直都有。

这是动图: 在此处输入图像描述

这是我如何应用属性(也许有不同的方法来应用属性指令?)

 <h1 [attr.colored]="check ? '': null">Testing something</h1>

这是指令:

 import {Directive, ElementRef} from '@angular/core'
@Directive({
    selector: '[colored]',
    host: {
        '(mouseenter)': 'onMouseEnter()',
        '(mouseleave)': 'onMouseLeave()'
    }
})

export class colorDirective {
    constructor(private el: ElementRef) {
    }
    onMouseEnter() { this.highlight("yellow"); }
    onMouseLeave() { this.highlight(null); }

    private highlight(color: string) {
        this.el.nativeElement.style.backgroundColor = color;
    }
}

编辑:有几个答案,但它们适用于 AngularJS (1)

原文由 Denko Mancheski 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 571
2 个回答

那是不支持的。仅当静态 HTML 与选择器匹配时才应用指令。

原文由 Günter Zöchbauer 发布,翻译遵循 CC BY-SA 3.0 许可协议

我知道这是一个迟到的回复,但可能会对某人有所帮助。

您可以将条件作为输入传递给属性指令,

 <h1 colored [enable]="check">Testing something</h1>

然后在指令中

    import {Directive, ElementRef} from '@angular/core'

@Directive({
    selector: '[colored]',
    host: {
        '(mouseenter)': 'onMouseEnter()',
        '(mouseleave)': 'onMouseLeave()'
    }
})

export class colorDirective {

    @Input() enable: boolean = true;

    constructor(private el: ElementRef) {
    }
    onMouseEnter() {
        if(this.enable){
            this.highlight("yellow");
        }
    }

    onMouseLeave() {
        if(this.enable){
            this.highlight(null);
        }
    }

    private highlight(color: string) {
        this.el.nativeElement.style.backgroundColor = color;
    }
}




原文由 Shashank Penumatcha 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题