【问题标题】:Angular 5, component is being initialized with no reasonAngular 5,组件正在无缘无故地初始化
【发布时间】:2019-03-21 16:11:29
【问题描述】:

我有以下问题-

组件 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 方法,在depositFormDataService.mainForm.links 中更新了我的formGroup

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()被调用,exl-file-list-itemesp-deposit-link-metadataconstructors被调用,所有视图都被刷新,我没有理由。

【问题讨论】:

  • 谢谢!关于您之前给我的“[(ngModel)]="description" (ngModelChange)="onChangeDescription()" 评论 - 如果我写 [ngModel],描述字段根本不会更新..

标签: javascript angular typescript angular-reactive-forms


【解决方案1】:

每当您对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 `

【讨论】:

  • 虽然我看到了这个-stackoverflow.com/questions/42244690/…按照它应该不会再渲染内容了。
  • 如果不查看整个代码,很难说出确切的问题,但是您可以使用trackBy 修复它。更新了我的答案。
  • 添加“track by”组件不会重新初始化?
  • 是的,不会。这样我们就知道链接是否和以前一样,不需要重新迭代。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-27
  • 2016-04-17
  • 1970-01-01
  • 2017-03-13
  • 2020-03-06
  • 1970-01-01
  • 2018-08-13
相关资源
最近更新 更多