Angular 2中的组件通信

时间:2017-01-11 16:15:00

标签: angular

可能很简单,但我疯了。 第一个组件是父

export class CompaniesComponent {
  companies: Company[];
  companiesShown: Company[];
}
constructor(private _companiesService: CompaniesService) {
    this._companiesService.getCompanies().subscribe(data => {
        this.companies = JSON.parse( data.text() );
        this.companiesShowed = this.companies;
    });
}

模板是这样的:

..
<tr *ngFor="let company of companiesShowed">
    <td>{{ company.name }}</td>
</tr>
..
<app-pagination [data]="companies" [(dataShown)]="companiesShown"></app-pagination>

最后,孩子们是这样的:

export class PaginationComponent implements OnChanges {
  @Input() data: Object[];
  @Input() dataShown: Object[];
  ngOnChanges() {
    if (this.data != null && this.data.length > 0 ) {
        this.dataShown = this.data;
        console.log(this.dataShown);
    }
 }
}

Console.log给我正确的dataShown长度,但在父对象中总是未定义/零长度...为什么? 谢谢!

1 个答案:

答案 0 :(得分:0)

对于&#34;双向绑定&#34;喜欢

[(dataShown)]="companiesShown"

工作,你的孩子组件需要

@Input() dataShown: Object[];
@Output() dataShownChange: EventEmitter<Object[]> = new EventEmitter<Object[]>();

从子级到父级的更新发送,如

this.dataShownChange.emit([{x: 'y'}]);

另见https://angular.io/docs/ts/latest/guide/template-syntax.html#!#two-way