gpt4 book ai didi

angular - 将对象插入数组并 *ngFor 它

转载 作者:行者123 更新时间:2023-12-04 03:12:30 25 4
gpt4 key购买 nike

当我单击按钮 addRoom 时,我想添加一个对象到数组中。并在 View 中循环播放。但是我数组中的数据重复了。对不起我的英语,如果你听不懂,可以在评论中问我。谢谢阅读!

我的代码:html

<table class="booking-table">
<tr>
<th>ROOM</th>
<th>5 + YRS</th>
<th>0-5 YRS</th>
<th>PER NIGHT</th>
</tr>
<tr *ngFor="let item of Room">
<td>{{item.room}}</td>
<td>
<select [ngModel]="item.audutModel" (ngModelChange)="AddAdults($event)">
<option value="1">
1 Adults
</option>
<option value="2">
2 Adults
</option>
<option value="3">
3 Adults
</option>
</select>
</td>
<td>
<select [ngModel]="item.childModel" (ngModelChange)="AddChild($event)">
<option value="1">
1 Child
</option>
<option value="2" *ngIf=" this.Adults == 1 || this.Adults == 2 ">
2 Child
</option>
<option value="3" *ngIf=" this.Adults == 1 ">
3 Child
</option>
</select>
</td>
<td>{{item.pricePN}}</td>
</tr>
<button type="" (click)="AddRoom()">add room</button>

代码:

  AddAdults(Adults){
this.Adults = Adults;
console.log(this.Adults)
this.pricePerAd = 200;
this.price = 1000 + Adults*this.pricePerAd;

}

AddChild(child){
this.pricePerCh = 100;
this.price += child*this.pricePerCh;


}



AddRoom(){


this.audutModel = "audut";
this.childModel = "child";
this.RoomNumber = this.RoomNumber + 1 ;

this.audutModel = this.audutModel + this.RoomNumber;
this.childModel = this.childModel + this.RoomNumber;


this.object.room = this.RoomNumber;
this.object.audut = this.audutModel;
this.object.child = this.childModel;
this.object.pricePN = this.price;

this.Room.push(this.object)
}

最佳答案

您到处都在引用 this.object,因此这自动意味着数组中的所有对象都是相同的。您需要将每个项目作为唯一项目才能区分它们。

这是一个非常粗略的示例,您应该改进并进一步使用。另请注意命名约定,例如,我指的是 rooms = [] 而不是 Room = []。还可以考虑制作一个 Interface 用于 Room 模型。

好的,当添加一个新房间时,创建一个空对象并递增一个局部变量 idx,它引用数组中的索引,在添加一个房间之后,让我们递增它:

addRoom(){
this.rooms.push({room: this.idx+1, adult: null, child: null, pricePN: null})
this.idx++;
}

在您的模板中,使用双向绑定(bind),当您添加成人(和 child )时,这样我们就不需要调用单独的函数来添加该房间中 child 或 parent 的数量。但是当进行更改时,改为调用 calculate,传递索引 (i),该索引已在 rooms

的迭代中声明>
<select [(ngModel)]="item.adult" (change)="calculate(i)">

calculate-函数只是将金额与您的价格相加:

calculate(index) {
this.rooms[index].pricePN =
1000+this.rooms[index].adult*200+this.rooms[index].child*100;
}

你有很多变量,你基本上可以从中删除所有变量,除了数组的声明。

这是一个 DEMO 一起玩。

关于angular - 将对象插入数组并 *ngFor 它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43932891/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com