ngFor中的角度双向绑定

时间:2018-08-05 12:47:08

标签: angular

在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;
}

4 个答案:

答案 0 :(得分:3)

ngValue伪指令应作为attribute binding使用,它不是两种可绑定的伪指令。

[(ngValue)]="bk.Category"

应该是

[ngValue]="bk.Category"

答案 1 :(得分:1)

<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";

答案 2 :(得分:0)

Ngvalue不支持双向绑定,您可以使用(onChange)= yourChangeFunction()来获取/更新您的值。

答案 3 :(得分:0)

我们不能以两种方式绑定$result = validateTransaction(); $confirmationUrl = $result['confirmation']['confirmation_url']; 指令。

在这里,您像ngValue(方框中的Banana)那样使其成为2方向,此语法将值绑定为2方向。 对于指令,您应该单向执行[()](仅Box)。

因此您的声明[]应该为[(ngValue)]="bk.Category"