Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 conditionally add attribute directives

Tags:

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)

like image 980
Denko Mancheski Avatar asked May 27 '16 18:05

Denko Mancheski


People also ask

How do you do a conditional directive?

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.

What is the difference between @component and @directive in Angular?

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.

What is Ng ATTR?

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.

What are different types of directives in Angular?

The three types of directives in Angular are attribute directives, structural directives, and components.


1 Answers

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

like image 143
Günter Zöchbauer Avatar answered Sep 29 '22 05:09

Günter Zöchbauer