2017-05-27 55 views
1

觸發非冒泡事件清晰觀看基準比方說我們有圖片,我們要顯示的列表:角2結構性指令,經孩子

<div *ngFor="let image of images; let i = index"> 
    <div *appMaskImageOnError="i" #mydir> 
     <img [src]="image" alt="" (error)="mydir.remove()"> 
    </div> 
</div> 

如果我們想擺脫錯誤整個內部div。這怎麼可能?如何讓我的指令,只去除圖像不良

回答

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>