[英]Angular - two-way binding problem on ngFor loop
我正在 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();
}
一切都很好,但是當我單擊按鈕添加新的自定義部分時,如您所見,“無標題”是在新的和舊的(較早添加的)自定義部分的輸入中顯示的值,但跨度顯示另一個值(在此屏幕截圖中) - 值“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();
}
經過幾個小時的思考這個問題,我注意到我犯了一個多么簡單的錯誤。 輸入的 name 屬性在 ngFor 循環中應該是唯一的。 所以我改變了這個:
<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()"
/>
對此:
<input
class="uk-input uk-form-blank uk-text-bold uk-text-lead uk-padding-remove-left"
type="text"
name="sectionName-{{ customSectionIndex }}"
[(ngModel)]="customSection.sectionName
"
(ngModelChange)="getHtmlContent()"
/>
現在一切都很好。 謝謝你們試圖幫助我並發現錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.