Created
January 8, 2019 14:20
-
-
Save hollygood/17177dec3dc9e1c25d9c5d2062d0234c to your computer and use it in GitHub Desktop.
Angular 6 Pass Async Data to Child Components
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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