使用Angular的@ViewChild装饰器和Observables实现组件间的通信。首先,在父组件中定义一个Observable对象,将其传递给子组件,并在子组件中订阅该对象。当子组件中的修改发生时,通过该Observable对象发出通知,将通知发送给父组件,父组件接收到通知后,在调用ViewChild修饰的子组件的方法来更新HTML。
示例代码如下:
// parent.component.ts import { Component, ViewChild } from '@angular/core'; import { Subject } from 'rxjs';
@Component({
selector: 'parent-component',
template:
})
export class ParentComponent {
@ViewChild('htmlOutput', {static: false}) htmlOutput: ElementRef;
subject = new Subject();
onButtonClick() { this.subject.next('Button Clicked'); }
updateHtmlOutput(html: string) { this.htmlOutput.nativeElement.innerHTML = html; }
}
// child.component.ts import { Component, Input } from '@angular/core';
@Component({ selector: 'child-component', template: '' }) export class ChildComponent { @Input() subject: Subject;
ngOnInit() { this.subject.subscribe((msg) => { // handle the message and make updates to the HTML this.updateHtml(msg); }); }
updateHtml(msg: string) { // update the HTML this.htmlOutput.nativeElement.innerHTML = msg; }
}