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 don't know if you can apply directives based on a condition, but a workaround would be having 2 buttons and display them based on a condition.
<button *ngIf="!condition"></button>
<button *ngIf="condition" md-raised-button></button>
Edit: maybe this will be helpful.
Maybe it will help someone.
In the example below I have the my-button.component.html
and I want to apply the *appHasPermission
directive to the <button>
only if the role
attribute is set.
<ng-container *ngIf="role; else buttonNoRole" >
<ng-container *appHasPermission="role">
<!-- button with *appHasPermission -->
<ng-template *ngTemplateOutlet="buttonNoRole;"></ng-template>
</ng-container>
</ng-container>
<ng-template #buttonNoRole>
<!-- button without *appHasPermission -->
<button
mat-raised-button type="button"
[color]="color"
[disabled]="disabled"
[(appClickProgress)]="onClick"
[key]="progressKey">
<mat-icon *ngIf="icon">{{ icon }}</mat-icon> {{ label }}
</button>
</ng-template>
That way you don't duplicate the <button>
code.
As others have also stated, directives
can't be dynamically applied.
However, if you just want to toggle md-button
's style from flat to raised, then this
<button md-button [class.mat-raised-button]="isRaised">Toggle Raised Button</button>
would do the trick. Plunker
Passing null
to the directive removes it!
<button md-raised-button="condition ? true : null"></button>
This could be a solution too:
[md-raised-button]="condition ? 'true' : ''"
It's working for angular 4, ionic 3 like this:
[color]="condition ? 'primary' : ''"
where condition
is a function that decides if this is an active page or not. The whole code look like this:
<button *ngFor="let page of ..." [color]="isActivePage(page) ? 'primary' : ''">{{ page.title }}</button>
I am working with Angular Material
, adding an element on *ngIf
didn't work properly for me (the element would disappear inside many newly generated material HTML tags lol).
I don't know if it's a good practice, but I used OnChanges
and I had a sort of conditional directive - and it worked! :)
So this is how I solved it:
import { Directive, Renderer2, ElementRef, Input, OnChanges, SimpleChanges, AfterViewInit } from '@angular/core';
@Directive({
selector: '[appDirtyInputIndicator]'
})
export class DirtyInputIndicatorDirective implements OnChanges, AfterViewInit {
@Input('appDirtyInputIndicator') dirtyInputIndicator: boolean;
span = this.renderer.createElement('span');
constructor(private renderer: Renderer2, private el: ElementRef) {}
ngOnChanges(changes: SimpleChanges): void {
if (changes.dirtyInputIndicator && this.dirtyInputIndicator) {
this.renderer.appendChild(this.el.nativeElement, this.span);
} else {
this.renderer.removeChild(this.el.nativeElement, this.span);
}
}
ngAfterViewInit() {
this.renderer.addClass(this.span, 'dirty_input_badge');
}
}