簡體   English   中英

Angular 反應形式:如何預設值? (FormArray 包含對象)

[英]Angular Reactive Form : How to preset values ? (FormArray containing objects)

我正在嘗試實現經典的“更新對象”功能。

我有一張列出我所有產品的表格,每一行都有一個編輯按鈕,打開一個我想顯示產品屬性值的模式。

我們在這里關注的屬性是“角色”,它的值是一個對象數組,每個對象都從下拉列表中選擇。

我要預填的表格

我設法顯示了正確數量的對象(該示例中為 3 個),但沒有設置值,並且在每種情況下都選擇了默認選項。

我嘗試在該屬性上使用 angular 'patchValue()' function 但沒有成功。

這是我所擁有的 Typescript:

public personas = new FormArray([], [], []);

constructor(private fb: FormBuilder, public productService: ProductService) {
  this.productForm = this.fb.group({
      personas: this.personas,
    });
}

public onEdit(product: Product): void {
    if (product.personas.length > 0) {
     this.personaService.personas$.pipe(takeUntil(this._destroyed$)).subscribe((personas: Persona[]) => {
        const array = product.personas.filter(p => personas.some(p2 => p.id === p2.id));
        this.personas = this.fb.array(array.map(persona => new FormControl({
          id: persona.id,
          persona: persona.persona,
        })));
      });
    }
}

這就是我的模板中的內容:

<div class="form-group">
  <label for="personas">Personas</label>
  <div id="personas" formArrayName="personas">
    <div *ngFor="let persona of personas.controls; let i = index;" class="d-flex m-1">
      <select
        *ngIf="!(personaService.isFetchingPersonas$ |async) && (personaService.personas$ |async) as options"
         class="form-control">
        <option *ngFor="let option of options" [ngValue]="option">{{ option.persona }}</option>
      </select>
  </div>
</div>

謝謝您的幫助

!!! 編輯 !!!

我意識到,當我試圖實現我的目標時,我打破了創建新產品的過程,因為 Persona 屬性不再正確設置。

所以 Stackblitz 項目與上面的代碼片段略有不同。 因為我將我的項目 state 移回了它的功能。

堆棧閃電戰: https://angular-ivy-cnmqhx.stackblitz.io

hello.component.html的底部,我添加了這個小助手,以查看表單中的內容。

<pre>
{{ productForm.value | json }}
</pre>

然后我將ngOnInit更改為如下所示:

  public ngOnInit(): void {
    this.product.personas.forEach((persona: Persona) => {
      const option = this.options.find(x => x.id === persona.id);
      if (option) {
        this.addField(option);
      }
    });
  }

這里的想法是查找每個“選項”並將該選項放入 formArray,而不是“角色”。

還有一點簡化的addField方法

  public addField(persona = {}): void {
    (this.productForm.get("personas") as FormArray).push(
      new FormControl(persona)
    );
  }

工作堆棧閃電戰

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM