I am using Material 2 to add md-raised-button
. I want to apply this directive only if certain condition becomes true.
For example:
<
I couldn't find a nice existing solution, so i built my own directive which does this.
import { Directive, ElementRef, Input } from '@angular/core';
@Directive({
selector: '[dynamic-attr]'
})
export class DynamicAttrDirective {
@Input('dynamic-attr') attr: string;
private _el: ElementRef;
constructor(el: ElementRef) {
this._el = el;
}
ngOnInit() {
if (this.attr === '') return null;
const node = document.createAttribute(this.attr);
this._el.nativeElement.setAttributeNode(node);
}
}
Then your html:
<div dynamic-attr="{{hasMargin: 'margin-left' ? ''}}"></div>
yes it is possible.
html page with appActiveAhover directive :)
<li routerLinkActive="active" #link1="routerLinkActive">
<a [appActiveAhover]='link1.isActive?false:true' routerLink="administration" [ngStyle]="{'background':link1.isActive?domaindata.get_color3():none}">
<i class="fa fa-users fa-lg" aria-hidden="true"></i> Administration</a>
</li>
<li routerLinkActive="active" #link2="routerLinkActive">
<a [appActiveAhover]='link2.isActive?false:true' routerLink="verkaufsburo" [ngStyle]="{'background':link2.isActive?domaindata.get_color3():none,'color':link2.isActive?color2:none}">
<i class="fa fa-truck fa-lg" aria-hidden="true"></i> Verkaufsbüro</a>
</li>
<li routerLinkActive="active" #link3="routerLinkActive">
<a [appActiveAhover]='link3.isActive?false:true' routerLink="preisrechner" [ngStyle]="{'background':link3.isActive?domaindata.get_color3():none}">
<i class="fa fa-calculator fa-lg" aria-hidden="true" *ngIf="routerLinkActive"></i> Preisrechner</a>
</li>
directive
@Directive({
selector: '[appActiveAhover]'
})
export class ActiveAhoverDirective implements OnInit {
@Input() appActiveAhover:boolean;
constructor(public el: ElementRef, public renderer: Renderer, public domaindata: DomainnameDataService) {
}
ngOnInit() {
}
@HostListener('mouseover') onMouseOver() {
if(this.appActiveAhover){
this.renderer.setElementStyle(this.el.nativeElement, 'color', this.domaindata.domaindata.color2);
}
}
@HostListener('mouseout') onMouseOut() {
if(this.appActiveAhover){
this.renderer.setElementStyle(this.el.nativeElement, 'color', 'white');
}
}
}
If you just need to add an attribute in order to trigger CSS rules, you can use the below method: (this does not dynamically create/destroy a directive)
<button [attr.md-raised-button]="condition ? '' : null"></button>
Applied the same to your plunker: fork
Update:
How condition ? '' : null
works as the value:
When its the empty string (''
) it becomes attr.md-raised-button=""
, when its null
the attribute will not exist.
Update: plunker update: fork (version issues fixed, please note the question was originally based on angular 4)