无法读取未定义的 Angular 8 的属性“本机元素”

Sta*_*low 10 viewchild angular angular8

在我的 angular 应用程序版本从angular 7升级到angular 8 之后, 我遇到了像这样的行的复杂问题

export class followupComponent implements OnInit {
    @ViewChild('message') messageElement: ElementRef;

    constructor(){}
    ...
}
Run Code Online (Sandbox Code Playgroud)

我读到新定义需要static参数并更改代码

@ViewChild('message', { static: true })) messageElement: ElementRef;
Run Code Online (Sandbox Code Playgroud)

我认为问题已经解决了。

但是不,我接受运行时错误:

无法读取未定义的属性“nativeElement”

与此代码相关

HTML:

@ViewChild('message', { static: true })) messageElement: ElementRef;
Run Code Online (Sandbox Code Playgroud)

TS:

<div class="message">
    <div class="action-buttons">
        <img src="{{imgPath + '_Edit_Hover.png'}}" (click)="OnEdit(Followup)">
    </div>
    <textarea matInput #message [ngModel]="Followup.Message"></textarea>
</div>
Run Code Online (Sandbox Code Playgroud)

ElementRef角度 8的正确定义是什么,

或 - 如何解决这个问题?

ysf*_*ysf 13

<textarea matInput #message [ngModel]="Followup.Message"></textarea>这段代码可能需要一些逻辑来显示(例如*ngIf*ngFor在父节点上,或一些异步代码),这意味着需要一个更改检测周期才能显示它。

根据Angular 8 文档

static - 是否在更改检测运行之前解析查询结果(即仅返回静态结果)。如果未提供此选项,编译器将回退到其默认行为,即使用查询结果来确定查询解析的时间。如果任何查询结果在嵌套视图内(例如 *ngIf),则查询将在更改检测运行后解析。否则,它将在更改检测运行之前解决。

所以你应该设置staticfalse

@ViewChild('message', { static: false })) messageElement: ElementRef;

这是一个简单的演示https://stackblitz.com/edit/angular-qgwhcv

在上面的演示中,输入框在 3 秒后显示。如果static:false在输入显示后设置并单击编辑,它会成功聚焦输入。但是如果您static:true在输入显示后更改并单击编辑,您将在控制台中看到错误。

  • 在我的例子中使用 ```static:false``` 有效,谢谢@ysf (2认同)