Reputation: 31
I have a component with a single child component which I cannot access and change to code to. In order to make something work I need to access a variable inside the child component onInit of the parent component, however the child component is always late. Is there a way for me to subscribe to the variable (I've tried with RxJS, however I had no luck, maybe I just did something wrong). I used the view child and I can access the variable later, however onInit it is still undefined, is there a way for me to wait for it inside the onInit and then call the rest of the functions?
@ViewChild("test") test;
ngOnInit() {
// console.log(this.test.model.test1);
// const subject = new BehaviorSubject(this.test.model.test1);
// subject.subscribe(console.log);
// this.test.model.test1.toPromise().then(res => {console.log(res)});
}
Upvotes: 0
Views: 81
Reputation: 459
The child component will only be initialized once the template of your parent component was initialized like @kvetis mentioned. Therefore the earliest you can expect anything from your child is in your parents afterViewInit()
-life cycle hook.
Generally you would use the @Output
decorator on a childs property which can then emit either an event or a value (which is where rxjs
might join the picture). And bind to that output in your parents template:
...
@Output
_model = new Subject<MyModelType>();
...
ngOnInit() {
someLogic();
this.model.next(whatEver);
}
...
...
<child-selector (_model)="handleChildValue($event)">
...
...
handleChildValue(model: MyModelType) {
doStuffWithModel();
}
...
Alternatively your can use an EventEmitter
instead of a Subject
.
Upvotes: 0
Reputation: 7351
You can only read child data after the view has been checked, so use ngAfterViewInit
instead of ngOnInit
.
But you cannot use the data from child in template, because the template has already been checked so the changes won't propagate into the view. You'd have to call change detection manually.
Upvotes: 2