Reputation: 341
I have two components.Parent ( match compo ) and child ( filter compo ).I want to pass data from child to parent component.If i have static property then when i do something like this it works.3 gets printed. But if i have some subcribe method where i am getting data in the child and i try to access on this was in the parent compo then i get undefined on the matches property.
//filter compo ts file
test = 3;
this.matchService.getMatches().subscribe(matches => {
this.matches = matches['pageOfItems'];
})
//match compo html
<app-filter #varName></app-filter>
// match compo ts file
@ViewChild('varName') someElement;
ngAfterViewInit(): void {
console.log(this.someElement.test);
console.log(this.someElement.matches);
}
Upvotes: 1
Views: 371
Reputation: 382
this.matchService.getMatches()
of your child component (filter component) is async request. You will never exactly assure of that this async task will be completed before your parent component's ngAfterViewInit()
invoked. So send your child component updated value to parent component using EventEmitter. Try to add EventEmitter at your child component and emit the data to parent component.
Upvotes: 1
Reputation: 790
Since matchService.getMatches()
is an async
operation, you will not be able to use the data before it reaches the Filter component.
The right way to do it is using the @Output()
decorator (see the Angular guide) which helps you send an event with a payload from the Child component to the Parent component.
You can then emit()
the data from the Child component inside the .subscribe()
function call or whenever you need it.
Upvotes: 1
Reputation: 2610
One way to send data from a child component to a parent component is by using an Output and an EventEmitter.
A basic example could look like this:
@Component({
selector: 'child-component',
template: '<button (click)="onValueChanged(3)">Click me</button>'
})
class ChildComponent {
@Output() public valueChanged = new EventEmitter<number>();
onValueChanged(value: number) {
this.valueChanged.emit(value);
}
}
@Component({
template: '<child-component (valueChanged)="onValueChanged($event)"></child-component>'
})
class ParentComponent {
onValueChanged(value: number) {
console.log('value from child =', value);
}
}
Note how the parent 'subscribes' to the value changes in the template. You can pass any value at any time you want from the child component this way.
Upvotes: 1
Reputation: 206
Check for the Output property in the official documention the "Parent listens for child event" section.
https://angular.io/guide/component-interaction
Upvotes: 1