Angular 2有条件地添加属性指令 [英] Angular 2 conditionally add attribute directives

查看:235
本文介绍了Angular 2有条件地添加属性指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里看到两个问题,如何有条件地添加和删除项目上的属性(



此处是我如何应用属性(可能有一种不同的方式来应用属性指令?)

 < h1 [attr。有色] =检查?'':null>测试一些东西< / h1> 

这是指令:

 从'@ angular / core'导入{Directive,ElementRef} 
@Directive({
选择器:'[有色]',
主机:{
'(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)

解决方案

不支持。指令仅在静态HTML与选择器匹配时应用。


I've seen two questions here how to conditionally add and remove attributes on an item (Is it possible to conditionally display element attributes using Angular2?) but my question is if it is possible to add and remove attribute directives ? I am able to add and remove the attribute but Angular does not "compile" the attribute as an attribute directive but the attribute just sits there doing nothing. Here is an example of 2 tags:

The first one is the one that I am trying to conditionally apply the attribute directive and the second one has it all the time.

Here is the gif:

Here is how I am applying the attribute (maybe there is a different way to apply attribute directive?)

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

And here is the directive:

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;
    }
}

Edit: There are couple answers but they are for AngularJS (1)

解决方案

That is not supported. Directives are only applied when static HTML matches the selector.

这篇关于Angular 2有条件地添加属性指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆