英文:
Text fields reset to same value on adding new element to array
问题
我有一个名为courses的变量,它是一个对象数组。
在模板中,ngFor指令输出了这个数组的内容。
我的模板:
<div>
<div class="row" *ngFor="let relacao of courses; let i = index">
<div>
<input
type="text"
name="courses[i].label"
[(ngModel)]="courses[i].label"
/>
</div>
</div>
</div>
<div>
<button (click)="addCourse()">添加</button>
</div>
我的TypeScript:
addCourse() {
this.courses.push({ label: 'test' });
}
当我使用更改数组元素的值并向数组添加新项时,它会将所有标签重置为初始值(null)。
我需要输入值在向数组添加新记录时不被重置。有人可以帮助我吗?
英文:
I have a variable called courses which is an array of objects.
In the template, an ngFor outputs the content of this array.
my template:
<div>
<div class="row" *ngFor="let relacao of courses let i = index">
<div>
<input
type="text"
name="courses[i].label"
[(ngModel)]="courses[i].label"
/>
</div>
</div>
</div>
<div>
<button (click)="addCourse()">add</button>
</div>
my ts:
addCourse() {
this.courses.push({ label: 'test' });
}
When i change the value of an array element using the <input>and add a new item to the array, it resets all the labels to the initial value (null).
I need the input value not to be reset when adding a new record to the array. Can someone help me?
答案1
得分: 1
确切的代码似乎对我来说运行正常。
我仍然分享代码,请检查是否有任何差异。
<div>
<div class="row" *ngFor="let relacao of courses; let i = index">
<div>
<input
type="text"
name="courses[i].label"
[(ngModel)]="courses[i].label"
/>
</div>
</div>
</div>
<div>
<button (click)="addCourse()">add</button>
</div>
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
courses: { label: string }[] = [];
addCourse() {
this.courses.push({ label: 'test' });
}
}
英文:
The exact code seems to be working fine for me.
I am still sharing the code please check if there are any differences
<div>
<div class="row" *ngFor="let relacao of courses; let i = index">
<div>
<input
type="text"
name="courses[i].label"
[(ngModel)]="courses[i].label"
/>
</div>
</div>
</div>
<div>
<button (click)="addCourse()">add</button>
</div>
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
courses: { label: string }[] = [];
addCourse() {
this.courses.push({ label: 'test' });
}
}
答案2
得分: 0
I found the problem accidentally. Adding {{ i }} to the input name solved the problem.
<div>
<div class="row" *ngFor="let relacao of courses; let i = index">
<div>
<input
type="text"
name="courses[{{i}}].label"
[(ngModel)]="courses[i].label"
/>
</div>
</div>
</div>
Thank you all!
英文:
accidentally i found the problem. adding {{ i }} to the input name solved the problem
<div>
<div class="row" *ngFor="let relacao of courses let i = index">
<div>
<input
type="text"
name="courses[{{i}}].label"
[(ngModel)]="courses[i].label"
/>
</div>
</div>
</div>
thank you all!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论