我试图在不涉及模板文件的情况下将 bool 值从父组件传递到子组件。通过使用模板文件进行正常的父子通信我知道这一点,但不知道如何在不使用模板类的情况下进行通信。
这是我尝试过的方法,但我不确定这是否正确。
父组件.ts:
export class ParentComponent{
value1: boolean;
ngOnInit(){
if(condition){
this.value1=true;
}
}
}
子组件.ts:
export class Childcomponent{
@Input() value1: boolean;
}
最佳答案
向父组件添加一个可观察对象。
export class ParentComponent {
public value$: Subject<boolean> = new Subject();
public notifyChild(value: boolean) {
this.value$.next(value);
}
}
将父级注入(inject)子级并订阅。
export class ChildComponent implmenents OnDestroy {
private destroyed: Subject = new Subject<void>;
public constructor(parent: ParentComponent) {
parent.value$.pipe(takeUntil(this.destroyed)).subscribe((value)=>{ ... });
}
public ngOnDestroy() {
this.destroyed.next();
}
}
关于angular - 在 Angular 2 中将 bool 值从父组件传递给子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53068071/