您可以将其封装成一个指令:
@Directive({
selector: '[activeOnClick]',
// Optionally replace this both with properties marked
// with @HostBinding and @HostListener decorators
host: {
'[class.active]': 'clicked',
'(click)': '_toggle()'
}
})
export class ActiveOnClickDirective {
@Input('activeOnClick')
clicked = false;
_toggle(){
this.clicked= !this.clicked;
}
}
在模块中声明指令后,可以如下使用:
<div activeOnClick *ngFor="let opt of options; let i=index">
如果您想在模板中绑定指令的标志值:
<div [activeOnClick]="true" *ngFor="let opt of options; let i=index">
您甚至可以扩展它以在宿主元素上动态应用不同的类:
@Directive({
selector: '[classesOnClick]'
})
export class ClassesOnClickDirective {
@Input('classesOnClick')
clicked = false;
@Input()
set class(value: string[]| string){
let classes = Array.isArray(value) ? value : value.split(' ');
classes = classes.filter(class => !!class);
this._classes = classes;
}
private _classes: string [] = ['active'];
constructor(private element: ElementRef, private renderer: Renderer2){}
@HostListener('click')
_toggle(){
this.clicked = !this.clicked;
}
private _update(){
this._classes.forEach(class => {
if(this.clicked){
this.renderer.addClass(this.element.nativeElement, class);
}else{
this.renderer.removeClass(this.element.nativeElement, class);
}
});
}
}
然后使用如下:
<div [classesOnClick]="true" [classesOnClickClass]="['c1','c2']" *ngFor="let opt of options; let i=index">
<div [classesOnClick]="true" classesOnClickClass="c1 c2" *ngFor="let opt of options; let i=index">