angular2 - 组件之间的通信

时间:2016-01-24 19:17:53

标签: angular angular2-directives angular2-forms

我使用Angular2搜索组件之间的通信,但我需要的是有点不同。 我有这样的结构:

父亲 - >儿子 - >子

我的代码看起来像这样

父组件:

@Component({
selector: 'app',
templateUrl: './instituicao/components/instituicao.html',
directives: [InstituicaoForm, InstituicaoList]
})

export class InstituicaoCmp {}

我的instituicao.html

<instituicao-form>
    <div class="row">
        <instituicao-list></instituicao-list>
    </div>
</instituicao-form>

我只是在<instituicao-form>处有一个表单,当用户点击来自<instituicao-list>的表格列表的某个项目时,我想填充该表单 在<instituicao-list>

这样的事情
<tr role="row" *ngFor="#item of items | instituicaoPipe : searchItems">
          <td>{{item.id.idInstituicao}}</td>
          <td>{{item.descInstituicao}}</td>
          <td>
            <button class="btn btn-link" (click)="HERE I WANT TO POPULATE FORM AT INSTITUICAO-FORM COMPONENT(item)"> Editar</button>
          </td>
        </tr>

我的机构形式html只是一个包含<input type="text" [(ngModel)]="item.idInstituicao"

等字段的表单

我只能在<instituicao-form>使用ng-model执行此操作 并将我的列表放在<instituicao-form>

请有人帮我这个吗?

1 个答案:

答案 0 :(得分:2)

根据你的问题,我假设你想要这样的东西:

@Component({
  selector: 'app',
  directives: [InstituicaoForm, InstituicaoList],
  template: `
  <instituicao-form #form>
    <div class="row">
      <instituicao-list (selectionChanged)="#form.update($event)></instituicao-list>
    </div>
  </instituicao-form>`,
})
export class InstituicaoCmp {
}
@Component({
  selector: 'instituicao-list',
  template: `
    <tr role="row" *ngFor="#item of items | instituicaoPipe : searchItems">
      <td>{{item.id.idInstituicao}}</td>
      <td>{{item.descInstituicao}}</td>
      <td>
        <button class="btn btn-link" (click)="select(item)"> Editar</button>
      </td>
    </tr>`,
})
export class InstituicaoList {
  var items;
  @Output() selectionChanged: EventEmitter = new EventEmitter();
  select(item) {
    this.selectionChanged.emit(item);
  }
}
@Component({
  selector: 'instituicao-form',
  template: `
<form>
  ...
</form>`,
})
export class InstituicaoForm {
  var item;
  update(value) {
    this.item = value;
  }
}

未经测试