Angular Parent组件侦听子组件中的多个输入

时间:2018-08-10 23:16:41

标签: angular typescript data-binding angular-components

我有一个呈现多个输入的父子组件。每组输入都在数组内部。我正在循环数组并尝试显示/更新当前值。我正在努力使父级能够读取子级组件中的数据。输出{{f.value|json}}只会显示一堆空对象,里面没有任何东西。

我环顾了其他问题中提到的所有@Outputs,但它们似乎都与按钮单击有关。我该如何聆听孩子体内的多个输入?

import { Component, OnInit, Input } from '@angular/core';
import { Group } from './model/group';

@Component({
  selector: 'app-list-item',
  template: `
    <label>Name:</label><input type="text" name="name" [ngModel]="group.name">
    <label>Login:</label><input type="text" name="login" [ngModel]="group.login">
    <label>Address:</label><input type="text" name="address" [ngModel]="group.address">
  `
})
export class ChildComponent {
  @Input() group: Group;
}
import { Component, OnInit, Input } from '@angular/core';
import { Group } from './model/group';

@Component({
  selector: 'app-groups',
  template: `
    <form novalidate #f="ngForm" (ngSubmit)="save(f)">
      <div *ngFor="let group of groups; let i = index;">
        <div ngModelGroup="{{i}}">
          <app-list-item [group]="group"></app-list-item>
        </div>
      </div>
      {{f.value|json}}
      <button type="submit" [disabled]="f.invalid">save</button>
    </form>
  `
})

export class ParentComponent {

  public groups: Group[];

  ngOnInit() {
    this.getGroups();
  }

  getGroups(): void {
    this.groups = [
      {id: 1, name: "john", login: "john", "address": "123 main street"},
      {id: 2, name: "mark", login: "mark", "address": "23 main street"},
      {id: 3, name: "james", login: "james", "address": "44 main street"},
      {id: 4, name: "hayley", login: "hayley", "address": "55 main street"}
    ];
  }
}

0 个答案:

没有答案