angular4 组件间通信

父传子用@input

子传父用@output

例:子组件

<p>
    <span *ngFor="let star of stars;let i=index" class="glyphicon glyphicon-star" [class.glyphicon-star-empty]="star" (click)="clickStar(i)"></span>
    <span>{{rating | number:'1.0-2'}}星</span>  //保留两位小数
</p>
import { Component, OnInit ,Input ,Output,EventEmitter,OnChanges,SimpleChanges } from '@angular/core';

@Component({
  selector: 'app-stars',
  templateUrl: './stars.component.html',
  styleUrls: ['./stars.component.scss']
})
export class StarsComponent implements OnInit, OnChanges {

//发生改变时,初始化星级和输入框内容 ngOnChanges(changes: SimpleChanges):void{ this.stars = []; for(let i=1;i<=5;i++){ this.stars.push(i>this.rating) } } //input装饰器,星级评价的组件的rating属性应该由他的父组件传递给它 @Input() private rating:number = 0; @Output() private ratingChange:EventEmitter<number> = new EventEmitter(); //这里的名字一定要用属性名+Change才能在父组件中使用[(rating)]进行双向数据绑定 private stars:boolean[]; @Input() private readonly:boolean = true; constructor() { } ngOnInit() { } clickStar(index:number){ if(!this.readonly){ this.rating = index+1; this.ngOnInit(); this.ratingChange.emit(this.rating); } } }

父组件调用子组件,进行双向数据绑定

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