Zijah
Zijah

Reputation: 31

Tracking a change in a variable in Angular

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

Answers (2)

Chund
Chund

Reputation: 459

Your problem:

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.

Generall Communication between child and parent

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:

child.ts

...

@Output
_model = new Subject<MyModelType>();

...

ngOnInit() {
  someLogic();
  this.model.next(whatEver);
}
...

parent.html

...
<child-selector (_model)="handleChildValue($event)">
...

parent.ts

...

handleChildValue(model: MyModelType) {
  doStuffWithModel();
}

...

Alternatively your can use an EventEmitter instead of a Subject.

Upvotes: 0

kvetis
kvetis

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

Related Questions