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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值