javascript - Angular 5,组件正在无故初始化

标签 javascript angular typescript angular-reactive-forms

我有以下问题-

组件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。 link 是一个具有三个 formControl 的对象,其中一个是“description”。

每次 onChangeDescription() 被调用 exl-file-list-itemesp-deposit 的构造函数 -link-metadata 被调用,所有 View 都被刷新,我不知道为什么。

最佳答案

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

关于javascript - Angular 5,组件正在无故初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52847114/

相关文章:

javascript - 具有用户角色参数的 Angular2 路由 canActivate 和 AuthGuard (JWT)

具有 DomSanitizer 依赖性的 Angular 6 单元测试组件

typescript - 当TypeScript中出现 “Object is possibly null”错误时,我该怎么办?

javascript - 将一组回调函数减少为一个回调

javascript - 我们可以从维基词典 api 中获得所需的部分吗?

javascript - Angular manifest.json 行 : 1, 列 : 1, 意外 token

reactjs - Typescript:超时的正确类型是什么?

angular - Ionic2 两个 ion-datetime 彼此相邻

javascript - 链接到 anchor (ajax url)不会调用 onBeforeUnload

javascript - Async/await vs then 哪个性能最好?