作为解决方法,我可以为您提供以下解决方案:
Plunker示例角度v4
在这里,您可以创建将执行相同操作的专用指令:
Plunker示例
ngIf4.ts
class NgIfContext { public $implicit: any = null; }
@Directive({ selector: '[ngIf4]' })
export class NgIf4 {
private context: NgIfContext = new NgIfContext();
private elseTemplateRef: TemplateRef;
private elseViewRef: EmbeddedViewRef;
private viewRef: EmbeddedViewRef;
constructor(private viewContainer: ViewContainerRef, private templateRef: TemplateRef) { }
@Input()
set ngIf4(condition: any) {
this.context.$implicit = condition;
this._updateView();
}
@Input()
set ngIf4Else(templateRef: TemplateRef) {
this.elseTemplateRef = templateRef;
this.elseViewRef = null;
this._updateView();
}
private _updateView() {
if (this.context.$implicit) {
this.viewContainer.clear();
this.elseViewRef = null;
if (this.templateRef) {
this.viewRef = this.viewContainer.createEmbeddedView(this.templateRef, this.context);
}
} else {
if (this.elseViewRef) return;
this.viewContainer.clear();
this.viewRef = null;
if (this.elseTemplateRef) {
this.elseViewRef = this.viewContainer.createEmbeddedView(this.elseTemplateRef, this.context);
}
}
}
}