@@ -6,11 +6,14 @@ import {
66 EventEmitter ,
77 HostBinding ,
88 ContentChildren ,
9- QueryList
9+ QueryList ,
10+ OnDestroy
1011} from "@angular/core" ;
1112import { SelectionTile } from "./selection-tile.component" ;
1213import { NG_VALUE_ACCESSOR } from "@angular/forms" ;
1314import { TileSelection } from "./tile-selection.interface" ;
15+ import { Subject } from "rxjs" ;
16+ import { takeUntil } from "rxjs/operators" ;
1417
1518@Component ( {
1619 selector : "ibm-tile-group" ,
@@ -23,7 +26,7 @@ import { TileSelection } from "./tile-selection.interface";
2326 }
2427 ]
2528} )
26- export class TileGroup implements AfterContentInit {
29+ export class TileGroup implements AfterContentInit , OnDestroy {
2730 static tileGroupCount = 0 ;
2831 /**
2932 * The tile group `name`
@@ -52,6 +55,9 @@ export class TileGroup implements AfterContentInit {
5255
5356 @ContentChildren ( SelectionTile ) selectionTiles : QueryList < SelectionTile > ;
5457
58+ protected unsubscribe$ = new Subject < void > ( ) ;
59+ protected unsubscribeTiles$ = new Subject < void > ( ) ;
60+
5561 constructor ( ) {
5662 TileGroup . tileGroupCount ++ ;
5763 }
@@ -61,18 +67,40 @@ export class TileGroup implements AfterContentInit {
6167 onTouched = ( ) => { } ;
6268
6369 ngAfterContentInit ( ) {
64- this . selectionTiles . forEach ( tile => {
65- tile . name = this . name ;
66- tile . change . subscribe ( ( ) => {
67- this . selected . emit ( {
68- value : tile . value ,
69- selected : tile . selected ,
70- name : this . name
71- } ) ;
72- this . onChange ( tile . value ) ;
70+ const updateTiles = ( ) => {
71+ // remove old subscriptions
72+ this . unsubscribeTiles$ . next ( ) ;
73+
74+ // react to changes
75+ this . selectionTiles . forEach ( tile => {
76+ tile . name = this . name ;
77+ tile . change
78+ . pipe ( takeUntil ( this . unsubscribeTiles$ ) )
79+ . subscribe ( ( ) => {
80+ this . selected . emit ( {
81+ value : tile . value ,
82+ selected : tile . selected ,
83+ name : this . name
84+ } ) ;
85+ this . onChange ( tile . value ) ;
86+ } ) ;
87+ tile . multiple = this . multiple ;
7388 } ) ;
74- tile . multiple = this . multiple ;
75- } ) ;
89+ } ;
90+ updateTiles ( ) ;
91+
92+ this . selectionTiles . changes
93+ . pipe ( takeUntil ( this . unsubscribe$ ) )
94+ . subscribe ( _ => updateTiles ( ) ) ;
95+ }
96+
97+ ngOnDestroy ( ) {
98+ this . unsubscribe$ . next ( ) ;
99+ this . unsubscribe$ . complete ( ) ;
100+
101+ // takes care of tile subscriptions when tile-group dies
102+ this . unsubscribeTiles$ . next ( ) ;
103+ this . unsubscribeTiles$ . complete ( ) ;
76104 }
77105
78106 writeValue ( value : any ) {
0 commit comments