Reputation: 910
I'm trying to pass boolean value from parent to child component without involving template file. Normal parent to child communication by using template file I'm aware of that, but not getting idea how to communicate without using template class.
This is how I have tried, but I'm not sure this is correct approach or not.
Parent component.ts:
export class ParentComponent{
value1: boolean;
ngOnInit(){
if(condition){
this.value1=true;
}
}
}
Child component.ts:
export class Childcomponent{
@Input() value1: boolean;
}
Upvotes: 2
Views: 2567
Reputation: 54821
Add an observable to the parent component.
export class ParentComponent {
public value$: Subject<boolean> = new Subject();
public notifyChild(value: boolean) {
this.value$.next(value);
}
}
Inject the parent into the child and subscribe.
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();
}
}
Upvotes: 2