简体   繁体   中英

Angular two way binding in ngFor

In Anguar 6, I have an ngFor which includes a select field. The selected-value of this field should be bound to the Category Property of SeatBookingModel that i use in ngFor. As this is of type CategoryModel i could be able to display the .Price Property of the CategoryModel.

What am I doing wrong here? The value for Category is not beeing set. Template:

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

Parts of Controller:

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 directive directive should be used as attribute binding , its not two way bind able directive.

[(ngValue)]="bk.Category"

should be

[ngValue]="bk.Category"
<select [(ngModel)]="selectedOption">
      <option *ngFor="let bk of selectOptions" [ngValue]="bk.Category.Name">
        {{bk.Category.Name}}
      </option>
</select>
{{ "selectedOption: " + selectedOption }}

ts code:

// 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()来获取/更新您的值。

We can't bind ngValue directive as two way.

Here, you are making it 2-way like [()] (Banana in the box), this syntax binds the value two-way. For directives you should do one-way [] (Only Box).

So your statement [(ngValue)]="bk.Category" should be [ngValue]="bk.Category"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM