假设我们有一个要显示的图像列表:
<div *ngFor="let image of images; let i = index">
<div *appMaskImageOnError="i" #mydir>
<img [src]="image" alt="" (error)="mydir.remove()">
</div>
</div>
如果有错误,我们想摆脱整个内部div。这怎么可能?如何让我的指令只删除有缺陷的图像
你可以创建这样的指令
@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>
普伦克示例
如果您只想保留一个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>