在 Angular 7 中,ElementRef
类型不再是泛型,因此在使用它时会出现错误。要解决这个问题,可以使用类型断言来将 ElementRef
转换为泛型类型 ElementRef
。以下是一个示例代码:
import { Component, ElementRef, ViewChild } from '@angular/core';
@Component({
selector: 'app-example',
template: `
Hello World!
`
})
export class ExampleComponent {
@ViewChild('myDiv') myDiv: ElementRef;
ngAfterViewInit() {
const nativeElement = this.myDiv.nativeElement as HTMLElement;
nativeElement.style.backgroundColor = 'red';
}
}
在上面的示例中,我们使用 ViewChild
装饰器获取了 #myDiv
元素的引用,并将其类型注解为 ElementRef
。然后,在 ngAfterViewInit
生命周期钩子中,我们将 nativeElement
的类型断言为 HTMLElement
,以便可以访问其原生 DOM 属性和方法。
通过这种方式,我们可以绕过类型检查器对 ElementRef
的泛型错误,并正确地使用 ElementRef
。