簡體   English   中英

Angular 反應式表單:如何監聽 FormArray 的 FormControls 的變化

[英]Angular Reactive Form: How to listen to changes in FormControls of a FormArray

我正在使用 Angular v11.2.3 和 vTypeScript 4.1.5。 為我的項目使用反應式表單控件。

我有一個 object“藝術品”,它的屬性 imageUrls 是一個字符串數組作為它的 imageUrls。 JSON 表示如下所示:

{
  "title": "Mona Lisa",
  "description": "Portrait painting with a mysterious smile",
  ...
  "imageUrls": [
    "https://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg/1280px-Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg"
  ],
  ...
}

在這件藝術品的“編輯”視圖中,我想在表格旁邊渲染圖像。 我希望圖像部分在編輯圖像的 URL 時自動更新。 如何在不提交整個表單的情況下實現這種“自動更新圖像”?

我當前的模板如下所示:

<div fxFlex fxLayout fxLayoutAlign="start start">
  <!-- image container -->
  <div fxFlex="40" fxLayout="column" fxLayoutGap="10px">
    <div *ngIf="artworkForm.get('imageUrls')">
      <ng-container *ngFor="let imageUrl of getImageUrlCtrls(); index as i">
      <img [src]="imageUrl.value" alt="Picture {{i + 1}} of {{artworkForm.get('title')?.value}}"
           class="detailImage">
      </ng-container>
    </div>
  </div>

  <!-- form container -->
  <div fxFlex="60" fxLayout="column" fxLayoutAlign="center center">

    <!-- ~~~~~~~~~~~~~~~~~ form of the details ~~~~~~~~~~~~~~~~~~ -->
    <div class="detailForm">
      <form fxFlex fxLayout="column" fxLayoutAlign="center start"
        [formGroup]="artworkForm" (ngSubmit)="onSubmit()">
        ....
        <div class="row">
          <p>Image URLs:</p>
          <!-- without the type='button', the form will automatically submit when this button is clicked! -->
          <button type="button" *ngIf="editable()" mat-icon-button (click)="onAddImageUrl()">
            <mat-icon color="primary">add</mat-icon>
          </button>
        </div>

        <ng-container *ngIf="artworkForm.get('imageUrls')">
          <div class="row" fxLayoutAlign="flex-end"
               *ngFor="let imageUrl of getImageUrlCtrls(); index as i">
          <mat-form-field>
            <mat-label>image {{i + 1}} URL</mat-label>
            <input matInput [value]="imageUrl.value">
          </mat-form-field>

          <button type="button" *ngIf="editable()"
                  mat-icon-button
                  (click)="onDeleteImageUrl(i)">
            <mat-icon color="warn">delete_outline</mat-icon>
          </button>
          </div>
        </ng-container>
       ....
      </form>
    </div>
  </div>

我的組件如下所示:

export class ArtworkDetailComponent implements OnInit {
  
  artworkForm!: FormGroup;
  
  artwork: {[index: string]: any} = {} as Artwork;

  ....

  ngOnInit(): void {
    if (this.artworkId) {
      this.artwork = this.artworkService.getArtworkById(this.artworkId);
    }

    this.initForm();
  }

  private initForm(): void {
    ....
    const ffImageUrls = new FormArray([]);

    this.artwork.imageUrls.forEach((imageUrl: string, index: number) => {
          ffImageUrls.push(new FormControl({value: imageUrl, disabled: this.readOnly()}));
        });
    ....

    this.artworkForm = new FormGroup({
      ....
      imageUrls: ffImageUrls,
      ....
    });
  }
  
  getImageUrlCtrls(): FormControl[] {
    return (this.artworkForm.get('imageUrls') as FormArray).controls as FormControl[];
  }
}

目前,當我更改表單中的 url 時,同一頁面上的圖像 div 沒有更新。 任何幫助將不勝感激!

我閱讀了 Netanel Basal 的博客Angular Reactive Forms: The Ultimate Guide to FormArray並解決了我的問題。

我的錯誤出現在 html 模板中,在這一行:

<input matInput [value]="imageUrl.value">

當我將其更改為:

<input matInput [formContrl]="imageUrl">

當我更改表單中的 URL 時,圖像立即重新呈現。 耶!!!

為了讓事情更清楚,我將變量名 imageUrl 更改為 urlCtrl。

Netanel 的代碼在最新的 Angular 和最新的 TypeScript 版本中不起作用。 由於 html 模板中缺少類型轉換,編譯器會報錯。 所以組件TS代碼中的這個方法很關鍵:

getImageUrlCtrls(): FormControl[] {
    return (this.artworkForm.get('imageUrls') as FormArray).controls as FormControl[];
  }

暫無
暫無

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

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