value a have always listbox mat-chip-listbox a make to How

huangapple go评论92阅读模式
英文:

How to make a mat-chip-listbox always have a value

问题

想知道如何确保 mat-chip-listbox 总是至少有一个值

  1. <mat-chip-listbox
  2. aria-label="foo-bar"
  3. formControlName="fooBar"
  4. >
  5. <mat-chip-option *ngFor="let i of fooBars" [value]="i">
  6. {{ i }}
  7. </mat-chip-option>
  8. </mat-chip-listbox>
英文:

Was wondering how to make a mat-chip-listbox always have at least one value

  1. &lt;mat-chip-listbox
  2. aria-label=&quot;foo-bar&quot;
  3. formControlName=&quot;fooBar&quot;
  4. &gt;
  5. &lt;mat-chip-option *ngFor=&quot;let i of fooBars&quot; [value]=&quot;i&quot;&gt;
  6. {{ i }}
  7. &lt;/mat-chip-option&gt;
  8. &lt;/mat-chip-listbox&gt;

答案1

得分: 0

这实际上非常简单

你监听 change

  1. <mat-chip-listbox
  2. aria-label="foo-bar"
  3. formControlName="fooBar"
  4. (change)="patchFooBar($event)"
  5. >
  6. <mat-chip-option *ngFor="let i of fooBars" [value]="i">
  7. {{ i }}
  8. </mat-chip-option>
  9. </mat-chip-listbox>

如果值是 undefined,那么你就对值进行修补。
注意,你必须将其放在一个定时器中,以便在下一个生命周期中触发。

  1. patchFooBar(changes: MatChipListboxChange) {
  2. if (!changes.value) {
  3. setTimeout(() => {
  4. // 等待下一个变化
  5. this.myFormGroup.get('fooBar').patchValue(this.foobars[0])
  6. }, 0)
  7. }
  8. }

你也可以订阅 myFormGroup.valueChanges 事件

英文:

It's actually quite simple

you listen to the change

  1. &lt;mat-chip-listbox
  2. aria-label=&quot;foo-bar&quot;
  3. formControlName=&quot;fooBar&quot;
  4. (change)=&quot;patchFooBar($event)&quot;
  5. &gt;
  6. &lt;mat-chip-option *ngFor=&quot;let i of fooBars&quot; [value]=&quot;i&quot;&gt;
  7. {{ i }}
  8. &lt;/mat-chip-option&gt;
  9. &lt;/mat-chip-listbox&gt;

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.

  1. patchFooBar(changes: MatChipListboxChange) {
  2. if (!changes.value) {
  3. setTimeout(() =&gt; {
  4. // Wait next changes
  5. this.myFormGroup.get(&#39;fooBar&#39;).patchValue(this.foobars[0])
  6. }, 0)
  7. }
  8. }

You could also subscribe to the myFormGroup.valueChanges event

huangapple
  • 本文由 发表于 2023年6月2日 14:51:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76387787.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定