angular4 组件间通讯

1.父→子 input

parent.ts

import { Component } from '@angular/core';

@Component({
  selector: 'page-parent',
  templateUrl: 'parent.html',
})
export class ParentPage {
  i: number = 0;
  constructor() {
    setInterval(() => {
      this.i++;
    }, 1000)
  }
}

parent.html

<ion-header>
  <ion-navbar>
    <ion-title>Parent</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <h2>Parent</h2>
  <!--page-child为子组件标签,content指令是child.ts中用@Input定义的-->
  <page-child [content]="i"></page-child>
</ion-content>

child.ts

import { Component,Input } from '@angular/core';

@Component({
  selector: 'page-child',
  templateUrl: 'child.html',
})
export class ChildPage {
  @Input() 
  content:string;
  constructor() {}

child.html

<div>child:{{content}}</div>

2.子→父 output

angular提供了EventEmitter类来用于接收和发射数据,这里我们使用EventEmitteremit方法来向父组件发射数据。

child.ts

import { Component, EventEmitter, Output } from '@angular/core';

@Component({
  selector: 'page-child',
  templateUrl: 'child.html',
})

export class ChildPage {
  //定义输出属性,EventEmitter用来将属性发射出去,这里的泛型指定
  //了要发射出去的的数据类型
  @Output() 
  changeNumber: EventEmitter<number> = new EventEmitter();
  Number: number = 0;
  constructor() {
    setInterval(() => {
      this.changeNumber.emit(++this.Number);
    }, 1000)
  }
}

child.html

<div>child</div>

parent.ts

import { Component } from '@angular/core';

@Component({
  selector: 'page-parent',
  templateUrl: 'parent.html',
})
export class ParentPage {
  i: number = 0;

  numberIChange(event:number){
      this.i = event;
  }
}

parent.html

<ion-header>
  <ion-navbar>
    <ion-title>Parent</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <h2>Parent:{{i}}</h2>
   <!--这里将子组件的changeNumber属性与父组件的事件绑定,$event其实就是子组件发射出来的值number-->
  <page-child (changeNumber)="numberIChange($event)"></page-child>
</ion-content>

 3.父、子间双向绑定

使用[()]来进行父组件和子组件的双向数据绑定时,Output属性的名称 = Input属性+Change,如下

child.ts

  @Input()
  private rating:number=0;//当前星级,接收父组件productDetail传来的值

  @Output()
  private ratingChange:EventEmitter<number> = new EventEmitter();//星级变化,将当前的星级输出到父组件

  click(){
    this.ratingChange.emit(this.rating);//发射当前rating值出去,在父组件接收          
 }

parent.ts

 newRating:number = 5;

parent.html

 <app-stars [(rating)]="newRating"></app-stars>

 

转载于:https://www.cnblogs.com/Caiyilong/p/8650138.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值