Skip to content

Commit bc829f0

Browse files
committed
feat(example app): handle option updates in material select view adapter
1 parent d089f00 commit bc829f0

File tree

1 file changed

+26
-4
lines changed

1 file changed

+26
-4
lines changed

example-app/src/app/material/mat-select-view-adapter.ts

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1-
import { Directive, forwardRef } from '@angular/core';
1+
import { AfterViewInit, Directive, forwardRef, OnDestroy } from '@angular/core';
22
import { MatSelect } from '@angular/material/select';
33
import { FormViewAdapter, NGRX_FORM_VIEW_ADAPTER } from 'ngrx-forms';
4+
import { Subscription } from 'rxjs';
45

56
// tslint:disable:directive-selector
67
// tslint:disable:directive-class-suffix
@@ -13,13 +14,31 @@ import { FormViewAdapter, NGRX_FORM_VIEW_ADAPTER } from 'ngrx-forms';
1314
multi: true,
1415
}],
1516
})
16-
export class NgrxMatSelectViewAdapter implements FormViewAdapter {
17-
constructor(private matSelect: MatSelect) { }
17+
export class NgrxMatSelectViewAdapter implements FormViewAdapter, AfterViewInit, OnDestroy {
18+
private value: any;
19+
private subscriptions: Subscription[] = [];
20+
21+
constructor(private matSelect: MatSelect) {}
22+
23+
ngAfterViewInit() {
24+
this.subscriptions.push(
25+
this.matSelect.options.changes.subscribe(() => {
26+
Promise.resolve().then(() => this.matSelect.writeValue(this.value));
27+
})
28+
);
29+
}
30+
31+
ngOnDestroy() {
32+
this.subscriptions.forEach(s => s.unsubscribe());
33+
}
1834

1935
setViewValue(value: any) {
36+
this.value = value;
37+
2038
// we have to verify that the same value is not set again since that would
2139
// cause focus to get lost on the select since it tries to focus the active option
2240
const selectedOption = this.matSelect.selected;
41+
2342
if (selectedOption) {
2443
if (Array.isArray(selectedOption) && Array.isArray(value)) {
2544
if (value.length === selectedOption.length && value.every((v, i) => v === selectedOption[i])) {
@@ -38,7 +57,10 @@ export class NgrxMatSelectViewAdapter implements FormViewAdapter {
3857
}
3958

4059
setOnChangeCallback(fn: any) {
41-
this.matSelect.registerOnChange(fn);
60+
this.matSelect.registerOnChange(value => {
61+
this.value = value;
62+
fn(value);
63+
});
4264
}
4365

4466
setOnTouchedCallback(fn: any) {

0 commit comments

Comments
 (0)