Angular 5:如何正确绑定* ngFor中的输入

时间:2018-05-17 15:05:08

标签: angular data-binding binding angular5 bind

我正在编写一些简单的应用程序来学习Angular 5(它将连接到ASP.NET CORE WEB API),我遇到了与* ngFor相关的问题。我找不到解决问题的方法来解决绑定数据的问题。

html的

<div class="CreateSettleParticipantBlock">
    <h1>Participants</h1>
    <div class="form-group" *ngFor="let participant of model.participants; let i = index">
        <label for="name">Person {{ i + 1 }}</label>
        <input type="text" class="form-control" id="participant{{i}}" name="participant{{i}}" ([ngModel])="participant.name">
    </div>
    <button type="button" class="btn btn-info" (click)="addNewParticipant()">Add new person</button>
</div>

组件.ts文件

import {Component, OnInit} from '@angular/core';
import {Settle} from "../settle";
import {Participant} from "../participant";
import {SettleService} from "../settle.service";
import {Currency} from "../currency";
import {Router} from "@angular/router";
import {UUID} from 'angular2-uuid';
import {AppConfig} from "../config/app.config";

@Component({
  selector: 'app-create',
  templateUrl: './create.component.html',
  styleUrls: ['./create.component.css']
})

export class CreateComponent implements OnInit {
  submitted = false;
  currencies = new Array<Currency>();
  settles = new Array<Settle>();

  private frontEndpoint = AppConfig.endpoints.front;

  public model: Settle;

  constructor(private settleService: SettleService, private router: Router) {
  }

  ngOnInit() {
    this.getCurrencies();
    this.getSettles();

    this.model = new Settle();
    this.model.participants = [{ name: ''}];
  }

  onSubmit() {
    this.model.token = UUID.UUID();

    this.settleService
      .addSettle(this.model)
      .subscribe(settle => this.settles.push(settle));

    this.router.navigate([`${this.frontEndpoint}/settle/${this.model.token}`]);

    this.submitted = true;
  }

  addNewParticipant(): void {
    this.model.participants.push(new Participant(''));
  }

  getCurrencies(): void {
    this.settleService
      .getCurrencies()
      .subscribe(currencies => this.currencies = currencies);
  }

  getSettles(): void {
    this.settleService
      .getSettles(1)
      .subscribe(settles => this.settles = settles);
  }
}

这是现在发送到后端的数据(json):

{
    "participants": [
        {
            "name": ""
        }
    ],
    "name": "Test 4",
    "currencyId": "1",
    "email": "tmkzmu@gmail.com",
    "creatorName": "Tom",
    "token": "ceac654e-fb7d-9ae5-9077-bf045379ceb2"
}

你可以看到参与者和他们的名字都是空的,即使我写了一些值。你能说出我做错了什么吗?我认为这里出了点问题:

<input type="text" class="form-control" id="participant{{i}}" name="participant{{i}}" ([ngModel])="participant.name">

0 个答案:

没有答案