英文:
How to make a mat-chip-listbox always have a value
问题
想知道如何确保 mat-chip-listbox 总是至少有一个值
<mat-chip-listbox
aria-label="foo-bar"
formControlName="fooBar"
>
<mat-chip-option *ngFor="let i of fooBars" [value]="i">
{{ i }}
</mat-chip-option>
</mat-chip-listbox>
英文:
Was wondering how to make a mat-chip-listbox always have at least one value
<mat-chip-listbox
aria-label="foo-bar"
formControlName="fooBar"
>
<mat-chip-option *ngFor="let i of fooBars" [value]="i">
{{ i }}
</mat-chip-option>
</mat-chip-listbox>
答案1
得分: 0
这实际上非常简单
你监听 change
<mat-chip-listbox
aria-label="foo-bar"
formControlName="fooBar"
(change)="patchFooBar($event)"
>
<mat-chip-option *ngFor="let i of fooBars" [value]="i">
{{ i }}
</mat-chip-option>
</mat-chip-listbox>
如果值是 undefined
,那么你就对值进行修补。
注意,你必须将其放在一个定时器中,以便在下一个生命周期中触发。
patchFooBar(changes: MatChipListboxChange) {
if (!changes.value) {
setTimeout(() => {
// 等待下一个变化
this.myFormGroup.get('fooBar').patchValue(this.foobars[0])
}, 0)
}
}
你也可以订阅 myFormGroup.valueChanges
事件
英文:
It's actually quite simple
you listen to the change
<mat-chip-listbox
aria-label="foo-bar"
formControlName="fooBar"
(change)="patchFooBar($event)"
>
<mat-chip-option *ngFor="let i of fooBars" [value]="i">
{{ i }}
</mat-chip-option>
</mat-chip-listbox>
If the value is undefined
then you patch the value.
Note, you have to put it in a timeout so it will be triggered in the next life circle.
patchFooBar(changes: MatChipListboxChange) {
if (!changes.value) {
setTimeout(() => {
// Wait next changes
this.myFormGroup.get('fooBar').patchValue(this.foobars[0])
}, 0)
}
}
You could also subscribe to the myFormGroup.valueChanges
event
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论