在Angular 8中,您可以使用Renderer2
来动态插入HTML元素,并使用@ViewChild
装饰器获取对插入元素的引用。以下是一个示例解决方法:
import { Component, ElementRef, Renderer2, ViewChild } from '@angular/core';
@ViewChild('container', { static: true }) container: ElementRef;
constructor(private renderer: Renderer2) {}
onWordAppear() {
console.log('Word appeared!');
}
ngOnInit() {
const button = this.renderer.createElement('button');
this.renderer.setProperty(button, 'innerText', 'Click me');
this.renderer.listen(button, 'click', this.onWordAppear.bind(this));
this.renderer.appendChild(this.container.nativeElement, button);
}
完整的组件类示例代码如下:
import { Component, ElementRef, Renderer2, ViewChild } from '@angular/core';
@Component({
selector: 'app-your-component',
template: ''
})
export class YourComponent implements OnInit {
@ViewChild('container', { static: true }) container: ElementRef;
constructor(private renderer: Renderer2) {}
ngOnInit() {
const button = this.renderer.createElement('button');
this.renderer.setProperty(button, 'innerText', 'Click me');
this.renderer.listen(button, 'click', this.onWordAppear.bind(this));
this.renderer.appendChild(this.container.nativeElement, button);
}
onWordAppear() {
console.log('Word appeared!');
}
}
当组件初始化时,它将动态插入一个带有回调函数的按钮。当单击按钮时,将调用onWordAppear
方法,并在控制台中打印出"Word appeared!"。