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)
Currently, there is NO way to conditionally apply a directive to a component. This is not supported. The components which you have created can be added or removed conditionally. There is already an issue created for the same with angular2 , so it should be the case with angular4 aswell.
Component is used to break up the application into smaller components. But Directive is used to design re-usable components, which is more behavior-oriented. That is why components are widely used in later versions of Angular to make things easy and build a total component-based model.
ng-attr is used for add or not the attribute in context. If the expression {{undefined || null}} , the attribute is not added otherwise if has a value then attribute is added with the value {{ value }} . The most common cases is in interpolation.
The three types of directives in Angular are attribute directives, structural directives, and components.
That is not supported. Directives are only applied when static HTML matches the selector.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With