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

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

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

&lt;mat-chip-listbox
  aria-label=&quot;foo-bar&quot;
  formControlName=&quot;fooBar&quot;
&gt;
  &lt;mat-chip-option *ngFor=&quot;let i of fooBars&quot; [value]=&quot;i&quot;&gt;
    {{ i }}
  &lt;/mat-chip-option&gt;
&lt;/mat-chip-listbox&gt;

答案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

&lt;mat-chip-listbox
  aria-label=&quot;foo-bar&quot;
  formControlName=&quot;fooBar&quot;
  (change)=&quot;patchFooBar($event)&quot;
&gt;
  &lt;mat-chip-option *ngFor=&quot;let i of fooBars&quot; [value]=&quot;i&quot;&gt;
    {{ i }}
  &lt;/mat-chip-option&gt;
&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.

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

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:

确定