Skip to content

Commit d9ba13f

Browse files
tinayuangaoandrewseguin
authored andcommitted
fix(chips): do not set chips value if there's no ngControl or value (#7285)
1 parent 86bea91 commit d9ba13f

File tree

2 files changed

+38
-2
lines changed

2 files changed

+38
-2
lines changed

src/lib/chips/chip-list.spec.ts

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ describe('MatChipList', () => {
4141
InputChipList,
4242
MultiSelectionChipList,
4343
FalsyValueChipList,
44+
SelectedChipList
4445
],
4546
providers: [{
4647
provide: Directionality, useFactory: () => {
@@ -63,6 +64,21 @@ describe('MatChipList', () => {
6364
});
6465
});
6566

67+
describe('with selected chips', () => {
68+
beforeEach(async(() => {
69+
fixture = TestBed.createComponent(SelectedChipList);
70+
fixture.detectChanges();
71+
}));
72+
73+
it('should not override chips selected', () => {
74+
const instanceChips = fixture.componentInstance.chips.toArray();
75+
76+
expect(instanceChips[0].selected).toBe(true, 'Expected first option to be selected.');
77+
expect(instanceChips[1].selected).toBe(false, 'Expected second option to be not selected.');
78+
expect(instanceChips[2].selected).toBe(true, 'Expected third option to be selected.');
79+
});
80+
});
81+
6682
describe('focus behaviors', () => {
6783
beforeEach(async(() => {
6884
setupStandardList();
@@ -1027,3 +1043,21 @@ class FalsyValueChipList {
10271043
control = new FormControl();
10281044
@ViewChildren(MatChip) chips: QueryList<MatChip>;
10291045
}
1046+
1047+
@Component({
1048+
template: `
1049+
<mat-chip-list>
1050+
<mat-chip *ngFor="let food of foods" [value]="food.value" [selected]="food.selected">
1051+
{{ food.viewValue }}
1052+
</mat-chip>
1053+
</mat-chip-list>
1054+
`
1055+
})
1056+
class SelectedChipList {
1057+
foods: any[] = [
1058+
{ value: 0, viewValue: 'Steak', selected: true },
1059+
{ value: 1, viewValue: 'Pizza', selected: false },
1060+
{ value: 2, viewValue: 'Pasta', selected: true },
1061+
];
1062+
@ViewChildren(MdChip) chips: QueryList<MdChip>;
1063+
}

src/lib/chips/chip-list.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -570,8 +570,10 @@ export class MatChipList implements MatFormFieldControl<any>, ControlValueAccess
570570
// Defer setting the value in order to avoid the "Expression
571571
// has changed after it was checked" errors from Angular.
572572
Promise.resolve().then(() => {
573-
this._setSelectionByValue(this.ngControl ? this.ngControl.value : this._value, false);
574-
this.stateChanges.next();
573+
if (this.ngControl || this._value) {
574+
this._setSelectionByValue(this.ngControl ? this.ngControl.value : this._value, false);
575+
this.stateChanges.next();
576+
}
575577
});
576578
}
577579

0 commit comments

Comments
 (0)