在某些情况下,我想在单击按钮时清除“ viewContainer”,但显示错误
错误TypeError:无法读取未定义的属性'viewContainer'
请检查随附的代码以更好地理解。
注意:就我而言,您会看到,我在document.body
上添加了click事件,并将指令名称也保留为[ngIf](我知道这不是破坏者)
此外,我尝试在点击的监听器中设置this.ngIf = false;
,但也会产生相同的错误。
“错误TypeError:无法设置未定义的属性'ngIf'”
谢谢。
app.component.ts
import { Component, TemplateRef, Directive, ViewContainerRef, Input, ElementRef, Renderer, ViewChild, ViewChildren, HostListener } from '@angular/core';
@Component({
selector: 'my-app',
template: `
<div *ngIf="val">
Hello cpIf Directive.
</div>
`,
styles: [`h1 { font-family: Lato; }`]
})
export class AppComponent {
val: boolean = true;
}
@Directive({
selector: '[ngIf]'
})
export class CpIfDirective {
constructor(private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef,
private renderer: Renderer) {
//this.viewContainer.createEmbeddedView(this.templateRef);
}
ngAfterViewInit() {
//this.viewContainer.createEmbeddedView(this.templateRef);
this.renderer.listen(document.body, 'click', this.clearView);
}
@Input() set ngIf(condition: boolean) {
if (condition) {
this.viewContainer.createEmbeddedView(this.templateRef);
} else {
this.viewContainer.clear();
}
}
clearView(event: any) {
this.viewContainer.clear();
//this.ngIf = false;
}
}
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { HelloComponent, CpIfDirective } from './hello.component';
@NgModule({
imports: [BrowserModule, FormsModule, ReactiveFormsModule],
declarations: [AppComponent, HelloComponent, CpIfDirective],
bootstrap: [AppComponent]
})
export class AppModule { }
答案 0 :(得分:1)
您只是无法访问this
内的clearView
使用此:
this.renderer.listen(document.body, 'click', (event) => {
// Do something with 'event'
this.viewContainer.clear();
})
您没有将此引用传递给该clearView
函数
或像这样将容器引用传递给clearView
this.renderer.listen(document.body, 'click', (event) => {
// Do something with 'event'
this.clearView(event, this.viewContainer)
})
clearView(event: any, element) {
element.clear();
//this.ngIf = false;
}
哦,是的,最重要的是,箭头功能可以在不做任何更改的情况下正常工作,对不起,我以前没有考虑过这个问题:)
箭头函数不会创建自己的上下文,因此具有 它的原始含义来自封闭的上下文。
clearView = (event: any) => {
this.viewContainer.clear();
//this.ngIf = false;
}