Let's create a directive that enables toggling between fa-eye
and fa-eye-slash
classes:
Directive code:
import { Directive, HostListener, ElementRef, Renderer2 } from '@angular/core';
@Directive({
selector: '[appToggleIcon]'
})
export class ToggleIconDirective {
constructor(private renderer: Renderer2) { }
private flag = true
@HostListener('click', ['$event']) onClick($event: Event) {
this.flag = !this.flag;
if (this.flag) {
this.renderer.removeClass($event.target, 'fa-eye');
this.renderer.addClass($event.target, 'fa-eye-slash')
}
else {
this.renderer.removeClass($event.target, 'fa-eye-slash');
this.renderer.addClass($event.target, 'fa-eye');
}
}
}
How to use the directive:
<span>
<i class="fa fa-eye" appToggleIcon>Button3 </i>
</span>
<br>
<span>
<i class="fa fa-eye" appToggleIcon>Button2 </i>
</span>
<br>
<span>
<i class="fa fa-eye" appToggleIcon>Button1 </i>
</span>
DEMO: Check how clicking the buttons changes their class.