【发布时间】:2020-09-14 17:59:40
【问题描述】:
我正在 Angular 10 中编写一个项目,但我不知道为什么,但是通过输入显示的属性与在 ngFor 循环中使用插值显示的相同属性不同。每次我将新的 customSection 推送到 customSections 数组时,这些值都会开始不同。
html部分:
<div
class="uk-margin-top"
*ngFor="
let customSection of resume.customSections;
let customSectionIndex = index
"
>
<input
class="uk-input uk-form-blank uk-text-bold uk-text-lead uk-padding-remove-left"
type="text"
name="sectionName"
[(ngModel)]="customSection.sectionName
"
(ngModelChange)="getHtmlContent()"
/>
<span>{{ customSection.sectionName }}</span>
打字稿部分:
onCustomSectionAddClick() {
this.resume.customSections.push(new CustomSection("Untitled"));
this.getHtmlContent();
}
一切都很好,但是当我单击按钮添加新的自定义部分时,如您所见,“无标题”是新旧(较早添加)自定义部分的输入中显示的值,但 span 显示其他值(在此屏幕截图上 - 值“b”)。有谁知道为什么会发生这种情况?
我做了一些解决方法以使其正常工作,但我仍然知道这只是 hack(不是好的解决方案):
html端:
<input
class="uk-input uk-form-blank uk-text-bold uk-text-lead uk-padding-remove-left"
type="text"
name="sectionName"
(change)="onCustomSectionNameChange($event, customSectionIndex)"
value="{{ customSection.sectionName }}"
/>
<span>{{ customSection.sectionName }}</span>
打字稿方面:
onCustomSectionNameChange(event: any, index: number) {
this.resume.customSections[index].sectionName = event.target.value;
this.getHtmlContent();
}
【问题讨论】:
-
单击按钮后您没有清除
customerSection。这不会自动发生。另外,getHtmlContent()做了什么,为什么每次更改后都要执行它? -
@n9iels 我编辑了我的帖子以展示如何使其正常工作(hack)。 getHtmlContent() 方法只是将数据发送到 API,仅此而已
-
我试图在 StackBlitz 上重现您的示例,但无法重现该错误。也许你没有提供什么是罪魁祸首?这里是 StackBlitz 的链接:stackblitz.com/edit/angular-ivy-kokush?file=src/app/…
标签: angular typescript