Angular Observables Subscribe

The example below shows an Observable input into a child component, as its a stream that can change you need to subscribe to those changes and use a change detector to update the template.

If possible rather do the subscription in the parent component and input the data. Example @Input() public inputType: IInputType;

child.component

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
child.component.ts

import { ChangeDetectorRef } from '@angular/core';
...

@Component({
...
})
export class ChildComponent implements OnChanges, OnDestroy {

@Input() public observable$: Observable<IInputType>;
private _destroyed$: Subject<any> = new Subject<any>();

public someString: string;

constructor (
private _changeDetectorRef: ChangeDetectorRef
) { }

public ngOnChanges () {
this.observable$.pipe(
takeUntil(this._destroyed$))
.subscribe(inputType => {
this.setSomeString(inputType);
this._changeDetectorRef.markForCheck();
});
}

public ngOnDestroy () {
this._destroyed$.next();
}

private setSomeString (inputType: IInputType): void {
this.someString = inputType.someProperty;
}
}
1
2
3
4
child.component.html

<h2>child</h2>
<p> someString: {{someString}}</p>

Reference