1. 程式人生 > >angular4 組件間通信

angular4 組件間通信

clas from only com 1.0 發生 implement exp scss

父傳子用@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>

angular4 組件間通信