[英]Angular two way binding in ngFor
在Anguar 6中,我有一個ngFor,其中包括一個選擇字段。 該字段的selected-value應該綁定到我在ngFor中使用的SeatBookingModel的Category屬性。 由於這是CategoryModel類型,因此我可以顯示CategoryModel的.Price屬性。
我在這里做錯了什么? 未設置類別的值。 模板:
<form>
<table class="table">
<tbody *ngFor="let bk of seatsReserved; let in=index">
<tr>
<td>
<span>{{ bk.SeatNumber }} </span>
</td>
<td>
<select class="form-control" name="ddlCategory_{{in}}">
<option *ngFor="let cat of getCategories(bk.SeatNumber)" [(ngValue)]="bk.Category" >{{cat.Name}}</option>
</select>
</td>
<td>
<span>{{ bk.Category.Price }}</span>
</td>
</tr>
</tbody>
</table>
控制器部分:
export class SeatPlanComponent implements OnInit {
constructor(private route: ActivatedRoute, private dataService: DataService) {
}
seatsAlreadyTaken: Array<String>;
seatsReserved: Array<SeatBookingModel>;
getCategories(seatNr: String) {
let mock1 = new CategoryModel();
mock1.Id = 1;
mock1.Name = "Erwachsen";
mock1.Price = 27.00;
let mock2 = new CategoryModel();
mock2.Id = 2;
mock2.Name = "Student";
mock2.Price = 22.00;
return [mock1, mock2];
}
SeatBookingModel:
export class SeatBookingModel {
SeatNumber : String;
Category: CategoryModel;
}
CategoryModel:
export class CategoryModel {
Id : Number;
Name: String;
Price: Number;
}
ngValue
指令偽指令應該用作attribute binding
,它不是兩種可綁定的指令。
[(ngValue)]="bk.Category"
應該
[ngValue]="bk.Category"
<select [(ngModel)]="selectedOption">
<option *ngFor="let bk of selectOptions" [ngValue]="bk.Category.Name">
{{bk.Category.Name}}
</option>
</select>
{{ "selectedOption: " + selectedOption }}
ts代碼:
// the option you selected; this is the model you bind to the select element.
// this also will hold the selected option/value when you change the select
public selectOptions:SeatBookingModel[] = [
{ SeatNumber : 'test1' , Category:{
Id : 44,
Name: 'test',
Price: 4,
}
}
];
public selectedOption = "test";
Ngvalue不支持雙向綁定,您可以使用(onChange)= yourChangeFunction()來獲取/更新您的值。
我們不能以兩種方式綁定ngValue
指令。
在這里,您使它像[()]
一樣為2路(在方框中為香蕉),此語法將值綁定為2路。 對於指令,您應該執行單向[]
(僅Box)。
因此,您的語句[(ngValue)]="bk.Category"
應該為[ngValue]="bk.Category"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.