Suhas Parameshwara的回答很好,但是它缺少了一个取消订阅以防止内存泄漏,这可能会让复制粘贴解决方案的人遇到问题。还有一个多余的Subject创建(它也是一个Observable,而不是Subject),如果你忘记向子组件传递Observable,就会隐藏一个错误。
以下是更完整的解决方案:
Parent.Component.html
<child-component [resetForm]="formResetter.asObservable()"></child-component>
<button (click)="resetChildForm()"></button>
Parent.Component.ts
import { Component } from '@angular/core';
import { Subject } from 'rxjs';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css'],
})
export class ParentClass {
public formResetter: Subject<boolean> = new Subject<boolean>();
resetChildForm() {
this.formResetter.next(true);
}
}
Child.Component.ts
import { Component, Input, OnDestroy, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css'],
})
export class ChildClass implements OnInit, OnDestroy {
@Input() resetForm: Observable<boolean>;
private sub: any;
ngOnInit() {
this.sub = this.resetForm.subscribe(response => {
});
}
ngOnDestroy(): void {
this.sub.ngUnsubscribe();
}
}