在使用ViewChild装饰器时,遇到可能导致事件抛出错误的情况。如果要避免错误,我们需要使用@ViewChild的静态选项来解决这个问题,并使用ElementRef来读取DOM元素。以下是示例代码:
import { Component, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'my-app',
template:
})
export class AppComponent {
@ViewChild('content', { static: true }) content: ElementRef;
onClick() { // 通过ElementRef访问DOM元素 this.content.nativeElement.innerText = 'Hello World!'; } }
在以上示例中,我们定义了一个按钮并在按钮上绑定了一个click事件。我们还定义了一个名为content的DOM元素,并使用@ViewChild将其读取为ElementRef。在onClick方法中,我们使用引用元素的内容属性来更新内容。
通过上述示例,我们可以避免在ViewChild装饰器组件中抛出错误。