javascript - 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
方法,更新了我formGroup
的depositFormDataService.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()
调用constructor
s 时都会刷新所有视图,我没有理由这样做。exl-file-list-item
esp-deposit-link-metadata
解决方案
每当您对 进行任何更改时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 `
推荐阅读
- google-cloud-platform - 谷歌云:如何列出授予用户或服务帐户的权限?
- excel - 使用 VB.NET 将 CSV 转换为 XLSX:分隔符错误
- excel - 在表中查找特定值
- java - 通过 Jenkins 运行时未捆绑 Jhipster/spring boot 静态资源 pdf 文件
- maven - Maven 项目无法在 Eclipse 中构建
- jasper-reports - Jasper Reports - 如何定位列表的元素
- javascript - 按键合并带下划线的数组
- grpc - gRPC - 我应该使用多少个存根/客户端?
- angular - 如何在 div 中制作类似的 [mat-dialog-close]?
- pdf - 使用大量代码示例调整 PDF 书籍的大小以适应较小的屏幕