你可以通过
Subject
在父组件中,创建一个主题,如下所示:
import { Component } from '@angular/core';
import { Subject } from 'rxjs';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
subject = new Subject<string>();
handleClick() {
// This will send a message via the subject
this.subject.next("TEST");
}
// Complete the subject when your component is destroyed to avoid memory leaks
ngOnDestroy() {
this.subject.complete();
}
}
<hello [notifier]="subject"></hello>
主题
import { Component, Input } from '@angular/core';
import { Subject } from 'rxjs';
@Component({
selector: 'hello',
template: `<h1>Hello {{name}}!</h1>`,
styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent {
@Input() notifier: Subject<any>;
ngOnInit() {
if (this.notifier != null) {
this.notifier.subscribe((event) => {
// This will be logged every time the subject.next is called.
console.log("HelloComponent heard", event);
})
}
}
}
这是一个
StackBlitz example