Angular-子父組件傳值與通訊

一、父組件給子組件傳值-@input
父組件不僅可以給子組件傳遞簡單的數據,還可以將自己的方法以及整個父組件傳給子組件
1.父組件調用子組件的時候傳入數據

<app-header [msg]="msg"></app-header>

2.子組件引入Input模塊

Import{Component,OnInit,Input} from '@anjular/core';

3.子組件中@Input接受父組件出過來的數據

export class HeaderComponent implements OnInit{
  @Input() msg:string
  constructor() { }
  ngOnInit() {
  }
}

4.子組件中使用父組件的數據

<h2>這裏是頭部組件{{msg}}</h2>

二、子組件@Output觸發父組件的方法
1.子組件引入Output和Eventemitter

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

2.子組件中實例化EventEmitter

@Output() private outer=new EventEmitter<stirng>();

3.子組件通過EventEmitter對象outer實例廣播數據

sendParent(){
this.outer.emit('msg from child')
}

4.父組件調用子組件時,定義接受事件,outer就是子組件的EventEmitter對象

<app-header (outer)="runParent($event)"></app-header>

5.父組件接收到數據會調用自己的runParent方法,並拿到子組件的數據

runParent(msg:string){
alert(msg);
}

三、父組件通過@ViewChild主動獲取子組件的數據和方法
1.調用子組件給子組件定義一個名稱

<app-footer  #footerChild></app-footer>

2.引入ViewChild

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

3.ViewChild和子組件關聯

@ViewChild('footerChild') footer

4.調用子組件

run(){
this.footer.footerRun();
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章