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