首页 > 解决方案 > 为什么在使用自定义结构指令时调用事件处理程序时模板引用变量未定义?

问题描述

我在输入元素上有一个自定义结构指令。输入元素的 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
}

标签: javascriptangular

解决方案


推荐阅读