javascript - 为什么在使用自定义结构指令时调用事件处理程序时模板引用变量未定义?
问题描述
我在输入元素上有一个自定义结构指令。输入元素的 onBlur 事件处理函数接受两个模板元素引用变量 - 一个是对它自己的 NgModel 的引用,另一个是对模板中另一个 NgModel 的引用(在带有附加指令的元素之外)。
页面加载后,在调用 onBlur 时未定义第二个引用变量,但是如果我在第二个输入元素内单击,然后返回到第一个输入元素,则引用设置为 NgModel,正如在 Blur 事件中所预期的那样。
我已经搜索了所有内容,包括 Stack Overflow,但没有任何运气为什么会发生这种行为。我发现当使用 *ngIf 模板引用变量时,只能在结构指令创建的嵌套模板内工作,但这种行为是不同的。
我可以切换到对模板元素引用变量使用@ViewChild,这很有效,但我正在修改需要尽可能接近原始代码的现有代码。没有自定义结构指令,一切都按预期工作。
即使使用如下所示的简单指令也会发生这种情况。
指令片段
@Directive({ selector: '[appMyDirective]' })
export class MyDirective implements OnInit {
constructor(private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) {
ngOnInit() {
this.viewContainer.createEmbeddedView(this.templateRef);
}
}
模板 (HTML) 片段
<mat-form-field>
<input matInput [(ngModel)]="comments" name="comments" #commentsRef="ngModel" (blur)="handleCommentsBlur(commentsRef, titleRef)" *appMyDirective>
</mat-form-field>
<mat-form-field>
<input matInput [(ngModel)]="title" name="title" #titleRef="ngModel">
</mat-form-field>
组件 TS 片段
handleCommentsBlur(commentsRef: NgModel, titleRef: NgModel) {
// titleRef is undefined after blur event occurs
// However when user clicks in the title element and goes back to the comments then the titleRef holds a reference to the NgModel on the next comments onBlur event
}
解决方案
推荐阅读
- python - 使用两个文件之间的经度和纬度比较距离
- c# - 如何读表?
- python - 使用 PySide2 在关闭事件时来自 socketserver 的 ValueError
- java - SetLocation(int , int) 不工作
- r - 有没有一种简单的方法来计算基于多个点的线性回归斜率?
- ios - 如何在运行时更改 uiimageview 内容模式?
- django - 将 django-oscarapi API ROOT 扩展为自定义 API 类
- prolog - Prolog收回不止一个事实,然后断言
- java - 使用 IKVM 在 C# 中实现 Java 方法
- python - Python 3.4 与 2.7 中 super.__new__ 上的 TypeError