Reputation: 260
There is a scenario where I want to clear 'viewContainer' on button click but it is showing error
ERROR TypeError: Cannot read property 'viewContainer' of undefined
Please check attached code for better understanding.
Note: In my case, you will see, I've added click event on document.body
and also kept directive name as [ngIf](I know this is not the spoiler).
Also, I tried to set this.ngIf = false;
in my click's listener but that too generating the same error.
"ERROR TypeError: Cannot set property 'ngIf' of undefined"
Thanks in advance.
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 { }
Upvotes: 2
Views: 7852
Reputation: 13801
You are just not able to access this
inside clearView
use this:
this.renderer.listen(document.body, 'click', (event) => {
// Do something with 'event'
this.viewContainer.clear();
})
You are not passing this reference to that clearView
function
or pass the container reference to the clearView like this
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;
}
Oh yes, most importantly, arrow functions would work without changing anything, sorry I did not thought about this before :)
An arrow function does not create its own this context, so this has its original meaning from the enclosing context.
clearView = (event: any) => {
this.viewContainer.clear();
//this.ngIf = false;
}
Upvotes: 2