【发布时间】:2018-10-24 18:25:38
【问题描述】:
我有一种情况,我需要一个动态数组,就像预订表格一样,人们正在向列表中添加航班,但它可能是 1 个航班或 10 个航班。我做了一个虚拟的例子,我已经能够复制这个问题,我希望是我,而不是 Angluar 的问题。不管怎样,就在这里。
我从一个带有添加项目的按钮的空数组开始,这些项目与 *ngFor(下面的代码)绑定,下面的每个字段都在该数组中,我填充了 1-5 的“名称”值只是打字
然后我决定删除成功的3号
然后我决定添加一个新的,这就是一切都出错的地方。正如您在下面看到的,它再次成功添加了第 5 项,但其中应该包含 #5 的项现在是空白的。
然后我按下“创建数组”,它只是将数组转储到控制台,我看到下面的内容,值仍然存在,但未绑定到该 1 项的输入。
好的,现在是代码:
这是我的 HTML 模板文件:
<form name="form" #f="ngForm">
Name: <input class="input" type="text" name="Name" [(ngModel)]="model.Name"
#Name="ngModel" />
Description: <input class="input" type="text" name="Description"
[(ngModel)]="model.Description" #Description="ngModel" />
<br>
<button (click)="addThought()">New Thought</button>
<div class="Thought" *ngFor="let Thought of myObject.Thoughts;let i=index">
Thought Name:<input name="Name-{{i}}" [(ngModel)]=Thought.Name
#Thought.Name="ngModel" type="Text" /><br>
Thought Description:<input name="Description-{{i}}"
[(ngModel)]=Thought.Description #Thought.Description="ngModel" type="Text"
/>
<br>
<br>
<button (click)="removeThought(Thought)">Remove Thought</button>
</div>
<button (click)="CreateThought()">Create Arrays</button>
</form>
这是我的组件 TS 文件:
export class CreateThoughtComponent implements OnInit {
model: any = {};
myObject: customObject = new customObject;
constructor(private guid: Guid, private staticData: StaticDataService) {
}
ngOnInit() {
}
CreateThought() {
console.log(this.myObject);
}
addThought() {
let thought: Thought = new Thought;
this.myObject.Thoughts.push(thought);
}
removeThought(t: Thought) {
this.myObject.Thoughts = this.myObject.Thoughts.filter(item => item !==
t);
}
}
这里是一个对象中数组的声明
export class customObject {
Name: string;
Description: string;
Thoughts: Thought[];
constructor() {
this.Thoughts = new Array<Thought>();
}
}
export class Thought {
Name: string;
Description: string;
}
任何帮助或建议将不胜感激。
【问题讨论】: