在Angular 8中,你可以使用@ViewChild
装饰器来获取元素的引用,并将其传递给方法。下面是一个示例代码:
在你的组件模板中,你可以使用#
语法来为元素创建一个引用:
在你的组件类中,你可以使用@ViewChild
装饰器来获取元素的引用:
import { Component, ViewChild } from '@angular/core';
@Component({
selector: 'app-my-component',
template: `...`
})
export class MyComponent {
@ViewChild('myButton', { static: false }) myButton: ElementRef;
myMethod(element: ElementRef) {
// 这里可以访问元素的属性和方法
console.log(element.nativeElement.innerText);
}
}
在上面的示例中,@ViewChild('myButton', { static: false })
装饰器将元素的引用赋值给myButton
属性。然后,你可以将myButton
属性传递给myMethod
方法,并在方法中访问元素的属性和方法。
请注意,@ViewChild
装饰器的第二个参数{ static: false }
是可选的,并且用于告诉Angular在组件初始化之前是否应该查找元素的引用。设置为false
时,Angular将在组件初始化后查找元素的引用。