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');
}
}