Angular2 之父子组件交互方式

父子组件交互方式,这里介绍主要的三种方式

1.事件传值

下面以列表页和分页组件举例。

list.component.html

1 <pagination *ngIf="pageParams?.total>0" [pageParams]="pageParams" (changePageData)="changePageData($event)"></pagination>
2 /* 这里的ngIf是为了控制total,当total从接口获取到了返回值以后再显示分页组件 */

list.component.ts

1 @Component({
2     templateUrl: './list.component.html'
3 })
4 export class ListComponent {
5     changePageData(event) {
6         this.pageParams = event;
7         this.getPageData()  // 从分页组件获取page参数后重新获取list数据
8     }
9 }

pagination.component.html

import { Component, OnInit, OnChanges, Input, Output, EventEmitter } from '@angular/core';
@Component({
    template: `<button (click)="nextPage()">点我下一页<`
})
export class PaginationComponent {
    @Input() pageParams: any;
    // EventEmitter是一个帮你实现观察者模式的对象,用于管理一系列订阅者并向其发布事件的对象
    @Output() changePageData: EventEmitter<any> = new EventEmitter;
    nextPage() {
        this.pageParams.pageNo += 1;
        this.changePageData.emit(this.pageParams)  // 广播事件给父组件,触发父组件事件,可以emit参数过去
    }
}

2.局部变量

 下面使用简单的例子来说明模板局部变量的使用。

2.1.子组件childComponent

child.component.ts

import { Component } from '@angular/core';
@Component({
    template: ``
})
export class ChildComponent {
    show1(event) {
       alert('从父组件传来的值是:'+event);
    }
}

2.2.父组件parentComponent

parent.component.ts

import { Component } from '@angular/core';
@Component({
    template: `
        <button (click)="child.show1(str)">点我调用子组件事件</button>
        <child-selector #child></child-selector>
    `
})
export class ParentComponent {
    str: string = '子组件你好!'
}

3.@ViewChild

原文地址:https://www.cnblogs.com/Failbs/p/9040383.html