Angular父子組件傳值(完整代碼見文后)
備注:這里父組件是news,子組件是footer
父組件->子組件
1) 子組件引入裝飾器
import { Component, OnInit,Input } from '@angular/core';
2) 父組件傳值
<app-header [title]="title"></app-header>
3) 子組件接收
@Input() title:string;//接收傳入的數據
4) 除了值,也可傳遞方法,或將整個組件傳遞給子組件
<app-header [title]="title" [run]="run" [home]="this"></app-header>
子組件->父組件
1) 使用ViewChild獲取子組件數據或方法
2) 使用@Output和EventEmitter觸發父組件的方法
i.子組件引入-----
import { Component, OnInit,Output,EventEmitter } from '@angular/core';
ii.子組件實例化output對象--------
@Output() private outer=new EventEmitter();
iii. 子組件廣播數據(按鈕觸發)
sendParent():void{ // alert(11); this.outer.emit("我是子組件數據");//廣播 }
iv. 父組件接收數據,並調用get方法------
<app-foo (outer)="get($event)"></app-footer>
完整代碼:
父組件:
html
<p>news works!</p> <button (click)="getData()">獲取子組件的數據</button> <button (click)="run()">獲取子組件的方法</button> <app-footer #footer (outer)="get($event)"></app-footer>
TS
import { Component, OnInit,ViewChild } from '@angular/core'; @Component({ selector: 'app-news', templateUrl: './news.component.html', styleUrls: ['./news.component.css'] }) export class NewsComponent implements OnInit { @ViewChild('footer') footer:any; constructor() { } ngOnInit(): void { } getData():void{ alert(this.footer.msg); } run():void{ this.footer.run(); } get(e):void{ alert("父組件收到廣播,執行get方法"); alert(e);//子組件廣播的數據 } }
子組件:
html
<p>footer works!</p> <button (click)="sendParent()">通過output廣播數據</button>
TS
import { Component, OnInit,Output,EventEmitter } from '@angular/core'; @Component({ selector: 'app-footer', templateUrl: './footer.component.html', styleUrls: ['./footer.component.css'] }) export class FooterComponent implements OnInit { public msg:string="footer message"; constructor() { } @Output() private outer=new EventEmitter(); ngOnInit(): void { } run():void{ alert("footer run!"); } sendParent():void{ // alert(11); this.outer.emit("我是子組件數據");//廣播 } }