父傳子用@inputcss
子傳父用@outputhtml
例:子組件app
<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); } } }
父組件調用子組件,進行雙向數據綁定this
<app-stars [(rating)]="newRating" [readonly]="false"></app-stars>