首页 > 解决方案 > Angular 5,组件正在无缘无故地初始化

问题描述

我有以下问题-

组分A:

<!-- LIST OF URLs-->
<exl-file-list  
  *ngIf="hasLinks()"
  listTitle="Added links:"
  [expandable]="editableFiles"
  expandAllButton="Edit metadata"
  (edit)="onLinkEdit($event)"
  (expandAll)="allLinksEditable = !allLinksEditable"
  (removeAll)="onRemoveAllLinks()">

  <!-- URL items -->
  <exl-file-list-item
    *ngFor="let link of depositFormDataService.mainForm.value.links let index = index"
    [item]="link"
    [index]="index"
    (remove)="onLinkRemove($event)"
    (edit)="onLinkEdit($event, index)">

    <!-- metadata of each URL -->
    **<esp-deposit-link-metadata
    [index]="index">
    </esp-deposit-link-metadata>**

  </exl-file-list-item>
</exl-file-list>

组件 B-esp-deposit-link-metadata:

<div class="metadata-container">
  <mat-form-field class="hasnt-underline">
    <mat-label>Description</mat-label>
    <textarea 
      matInput 
      [(ngModel)]="description" 
      **(ngModelChange)="onChangeDescription()" 
      ** #textarea placeholder="Describe the link" 
      matTextareaAutosize></textarea>
  </mat-form-field>
</div>

onChangeDescription方法,更新了我formGroupdepositFormDataService.mainForm.links

onChangeDescription(){
  this.depositFormDataService
    .updateLinkDescription(this.index,this.description);
}

它的内容:

updateLinkDescription(index, description){
  const link = this.links.at(index) as FormGroup;
  link.setControl('description', new FormControl(description));
}

depositFormDataService.mainForm 将链接保存为 FormArray。链接是具有三个 formControls 的对象,其中一个是“描述”。

每次调用和onChangeDescription()调用constructors 时都会刷新所有视图,我没有理由这样做。exl-file-list-itemesp-deposit-link-metadata

标签: javascriptangulartypescriptangular-reactive-forms

解决方案


每当您对 进行任何更改时depositFormDataService.mainForm.value.links,Angular 都会检测到更改并再次呈现内容。

由于您在内部使用了这两个组件*ngFor="let link of depositFormDataService.mainForm.value.links,因此它将重新初始化该组件。

在 ts

trackByLink = (index: number, link : any) => link.url; //check if you have `url` if not then you other unique property.

在 HTML 中

`*ngFor="let link of depositFormDataService.mainForm.value.links ; trackBy:trackByLink `

推荐阅读