在Angular中,可以使用ViewChild装饰器来获取动态创建的DOM元素。
以下是一个示例:
在HTML模板中,我们动态创建了一个按钮,并给它一个标识符:
在组件类中,我们使用ViewChild装饰器来获取这个动态创建的按钮:
import { Component, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-my-component',
template: `
`,
})
export class MyComponent {
@ViewChild('myButton', { static: false }) myButton: ElementRef;
onButtonClick() {
console.log(this.myButton.nativeElement);
// 在控制台中输出动态创建的按钮元素
}
}
在上面的代码中,我们使用ViewChild装饰器来获取标识符为"myButton"的元素。通过设置static为false,表示元素是动态创建的,而不是在组件初始化时就存在的。
然后,我们可以在onButtonClick方法中访问myButton.nativeElement属性,来获取动态创建的按钮元素,并进行相应的操作。