您可以像
@Directive({
selector: '[appMaskImageOnError]'
})
export class AppMaskImageOnErrorDirective {
@Input() appMaskImageOnError: any;
constructor(private vcRef: ViewContainerRef, private templateRef: TemplateRef<any>) { }
ngOnInit() {
this.vcRef.createEmbeddedView(this.templateRef, { remove:() => this.remove() });
}
remove() {
this.vcRef.clear();
}
}
創建指令,然後你的模板應如下所示:
<div *ngFor="let image of images; let i = index">
<div *appMaskImageOnError="i; remove as del">
<img [src]="image" alt="" (error)="del()">
</div>
</div>
Plunker Example
如果您只想保留一個div
,則使用ng-container
<ng-container *ngFor="let image of images; let i = index">
<div *appMaskImageOnError="i; remove as del">
<img [src]="image" alt="" (error)="del()">
</div>
</ng-container>