Существует сценарий, в котором я хочу очистить 'viewContainer' при нажатии кнопки, но он показывает ошибку
ОШИБКА TypeError: Невозможно прочитать свойство 'ViewContainer' из неопределенного
Пожалуйста, проверьте прилагаемый код для лучшего понимания.
Примечание: В моем случае, вы увидите, я добавил событие click для document.body
, а также сохранил имя директивы как [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 { }