Skip to content

Instantly share code, notes, and snippets.

@hollygood
Created January 8, 2019 14:20
Show Gist options
  • Save hollygood/17177dec3dc9e1c25d9c5d2062d0234c to your computer and use it in GitHub Desktop.
Save hollygood/17177dec3dc9e1c25d9c5d2062d0234c to your computer and use it in GitHub Desktop.
Angular 6 Pass Async Data to Child Components
// blogger.component.ts
...
template: `
<h1>Posts by: {{ blogger }}</h1>
<div>
<posts [data]="posts"></posts>
</div>
`
...
// Option 1: Use ngOnChanges:
// posts.component.ts
...
ngOnChanges(changes: SimpleChanges) {
// only run when property "data" changed
if (changes['data']) {
this.groupPosts = this.groupByCategory(this.data);
}
}
...
// Option 2: Use BehaviorSubject
// posts.component.ts
...
// initialize a private variable _data, it's a BehaviorSubject
private _data = new BehaviorSubject<Post[]>([]);
// change data to use getter and setter
@Input()
set data(value) {
// set the latest value for _data BehaviorSubject
this._data.next(value);
};
get data() {
// get the latest value from _data BehaviorSubject
return this._data.getValue();
}
ngOnInit() {
// now we can subscribe to it, whenever input changes,
// we will run our grouping logic
this._data
.subscribe(x => {
this.groupPosts = this.groupByCategory(this.data);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment