Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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: enter image description here

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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
394 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...