Reputation: 13
I have a child component that takes an @Input value from a dropdown box of a parent component. This value has an array of objects that I want to pass as the data source to a table so I need to construct some Observable to maintain this and have it change when the @Input value changes, etc... I know this is a basic question but still wrapping my head around Angular design paradigm.
Given an @Input value as such:
@Input() parentObject: ParentObject
I have tried referencing the value directly like:
rowData = this.parentObject._rows;
This breaks because it is populated async so at runtime parentObject is initially undefined.
I have tried:
ngOnChanges(change: SimpleChanges){
if (changes.parentObject.currentValue){
rowData = changes.parentObject.currentValue._rows;
}
}
This breaks because the _rows is an array and not an Observable. I guess I could wrap the _rows into an Observable when I set it but that seems hacky.
Note that I'm not trying to pass the value back to a parent, just consume it within a table in the child component. I also experimented using a Subject and that compiles and runs fine but for some reason the table does not receive the updated data. I have included that code here so be more clear what I'm doing:
rowData = new Subject<Row[]>();
ngOnChanges(change: SimpleChanges){
if (changes.parentObject.currentValue){
this.rowData.next(changes.parentObject.currentValue._rows);
}
}
and in my .html:
<ag-grid-angular
style="width: 500px; height: 500px;"
class="ag-theme-balham"
[rowData]="rowData | async"
[columnDefs]="columnDefs">
</ag-grid-angular>
I'm sure there's some really basic way of doing this interaction that I'm not considering.
Upvotes: 1
Views: 533
Reputation: 6963
I like how Services work. Create a service component, name it EventService.... Then add eventEmitters like this, into the EventService.TS file.
SomeEvent = new EventEmitter<any>();
Then the parent and child components will each import the EventService
import { EventService } from "../../services/event.service";
Add this to the parent's and child's constructor:
private EventService: EventService,
When ready the parent will fire the event.
EventService.SomeEvent.Emit(data);
Make sure the child has subscribed to the event...
SomeEvent.Subscribe(data=>{//data is here});
Upvotes: 1