【发布时间】:2020-11-25 01:39:15
【问题描述】:
我遇到了@ViewChild 中的{static: false} 属性修复的以下问题。
这个 stackoverflow Q/A 帮助了 How should I use the new static option for @ViewChild in Angular 8?。
我想更好地理解这个场景以及static 如何改变结果,以及变化检测如何影响这个场景。我在 Angular 文档中阅读了一些关于更改检测的内容,发现非常缺乏。
我想出了一个堆栈闪电战来说明我不理解的东西。 Stackblitz angular example
当点击toggle 按钮两次时,我在命令行上得到以下信息:
> undefined undefined
> undefined undefined
> undefined ElementRef {nativeElement: div}
> undefined ElementRef {nativeElement: div}
但我希望:
> undefined undefined
> undefined ElementRef {nativeElement: div}
> ElementRef {nativeElement: div} ElementRef {nativeElement: div}
> ElementRef {nativeElement: div} ElementRef {nativeElement: div}
这是代码的逻辑——(参见 stackblitz 中的完整代码)
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
@ViewChild("contentPlaceholder", { static: true })
trueViewChild: ElementRef;
@ViewChild("contentPlaceholder", { static: false })
falseViewChild: ElementRef;
display = false;
constructor() {}
show() {
console.log(this.trueViewChild, this.falseViewChild);
this.display = true;
console.log(this.trueViewChild, this.falseViewChild);
}
}
我的问题是:
- 为什么
this.falseViewChild的第二行值显示为未定义。设置this.display = false后不应该运行更改检测,因此它不应该是未定义的吗? - 为什么
this.trueViewChild保持未定义。我希望它在*ngIf变为 true 后找到元素?
【问题讨论】:
标签: angular angular-ng-if viewchild