gpt4 book ai didi

angular - 当我想明确清除它时无法读取未定义的属性 'viewContainerRef'

转载 作者:搜寻专家 更新时间:2023-10-30 21:46:37 27 4
gpt4 key购买 nike

有一种情况,我想在单击按钮时清除“viewContainer”,但它显示错误

ERROR TypeError: Cannot read property 'viewContainer' of undefined

请检查附加代码以便更好地理解。

注意:在我的例子中,您会看到,我在 document.body 上添加了点击事件,并将指令名称保留为 [ngIf](我知道这一点不是剧透)。

此外,我尝试在我的点击监听器中设置 this.ngIf = false;,但这也产生了同样的错误。

"ERROR TypeError: Cannot set property 'ngIf' of undefined"

提前致谢。

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 { }

最佳答案

您只是无法在 clearView 中访问 this

使用这个:

this.renderer.listen(document.body, 'click', (event) => {
// Do something with 'event'
this.viewContainer.clear();
})

您没有将此引用传递给那个 clearView 函数

Demo

或者像这样将容器引用传递给 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;
}

哦,是的,最重要的是,箭头函数可以在不改变任何东西的情况下工作,抱歉我之前没有考虑过这个:)

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;
}

Ref

关于angular - 当我想明确清除它时无法读取未定义的属性 'viewContainerRef',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53955825/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com