ng-reflect-model 显示正确值但未反映在输入中
ng-reflect-model shows correct value but not reflecting in input
遇到一个非常奇怪的问题,即我的应用程序在一个非常特定的用户案例中行为不端。我有一个门户网站,用户可以在其中添加问题和答案,然后进行编辑。在这种情况下,当我删除一个 set(q+a) 然后尝试添加它时,模型正在更新,但我的视图从占位符中获取值并自行更新。这里我只是拼接和推送数组中的值并使用 ngFor 进行渲染。最后一个元素是一个虚拟元素,用于输入向上推的值。
如果有任何意义,请附上屏幕截图。
您可以看到,对于文本框,ng-reflect-model 显示正确的问题,但元素本身显示占位符文本。
显然,问题是由于 Angular 无法正确跟踪我的数组元素引起的。我很难发现这一点。所以只需向我的 ngFor 添加一个 trackBy 属性,我就能够解决这个问题。
将此添加到我的组件中:
customTrackBy(index: number, obj: any): any {
return index;
}
然后在模板中:
<div class="margin-bottom-15"
*ngFor="let assessment of language.assessments; trackBy:customTrackBy">
所以基本上我要求 angular 按索引跟踪我在数组中的元素。它解决了这个问题。
这里的评估是每个问答集的模型。
如果您使用嵌套的 ngFor,则名称属性可能不唯一。它应该是独一无二的。因此,在 name 属性后加上 for 循环的索引,使其唯一。
<form #f="ngForm" validate>
<div *ngFor="childItem of parentArray; index as pIndex;">
<div *ngFor="childArray of childItem.parameters;index as cIndex;">
First Name: <input name="childArray-{{pIndex+''+cIndex}}"
type="text" [(ngModel)]="childArray.firstname" required>
Last Name: <input name="childArray-{{pIndex+''+cIndex}}"
type="text" [(ngModel)]="childArray.lastname" required>
<button type="button" [disabled]="!f.valid"
(click)="submitForm();"> Submit </button>
</div>
</div>
</form>
否则你可以使用
*ngFor="childItem of parentArray; index as i;"
和
[attr.data-target]="'#test' + i"
和
name="test{{i}}
遇到一个非常奇怪的问题,即我的应用程序在一个非常特定的用户案例中行为不端。我有一个门户网站,用户可以在其中添加问题和答案,然后进行编辑。在这种情况下,当我删除一个 set(q+a) 然后尝试添加它时,模型正在更新,但我的视图从占位符中获取值并自行更新。这里我只是拼接和推送数组中的值并使用 ngFor 进行渲染。最后一个元素是一个虚拟元素,用于输入向上推的值。
如果有任何意义,请附上屏幕截图。
您可以看到,对于文本框,ng-reflect-model 显示正确的问题,但元素本身显示占位符文本。
显然,问题是由于 Angular 无法正确跟踪我的数组元素引起的。我很难发现这一点。所以只需向我的 ngFor 添加一个 trackBy 属性,我就能够解决这个问题。
将此添加到我的组件中:
customTrackBy(index: number, obj: any): any {
return index;
}
然后在模板中:
<div class="margin-bottom-15"
*ngFor="let assessment of language.assessments; trackBy:customTrackBy">
所以基本上我要求 angular 按索引跟踪我在数组中的元素。它解决了这个问题。
这里的评估是每个问答集的模型。
如果您使用嵌套的 ngFor,则名称属性可能不唯一。它应该是独一无二的。因此,在 name 属性后加上 for 循环的索引,使其唯一。
<form #f="ngForm" validate>
<div *ngFor="childItem of parentArray; index as pIndex;">
<div *ngFor="childArray of childItem.parameters;index as cIndex;">
First Name: <input name="childArray-{{pIndex+''+cIndex}}"
type="text" [(ngModel)]="childArray.firstname" required>
Last Name: <input name="childArray-{{pIndex+''+cIndex}}"
type="text" [(ngModel)]="childArray.lastname" required>
<button type="button" [disabled]="!f.valid"
(click)="submitForm();"> Submit </button>
</div>
</div>
</form>
否则你可以使用
*ngFor="childItem of parentArray; index as i;"
和
[attr.data-target]="'#test' + i"
和
name="test{{i}}