您好,登錄后才能下訂單哦!
這篇文章主要介紹Angular中父子組件間如何相互傳參,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!
也就是說 子組件給父組件傳數(shù)據(jù)和方法
通過ViewChild
演示例子:
父組件:news
子組件:header
假如子組件header有個(gè)run方法
run(){ console.log(‘我是header里面的run方法’); }
在父組件調(diào)用子組件header的run方法
1、在父組件中調(diào)用子組件,并給子組件定義一個(gè)名稱
<app-header #header></app-header>
2、在父組件引入ViewChild
import { Component,OnInit ,ViewChild} from ‘@angular/core’;
3、利用屬性裝飾器ViewChild 和剛才的子組件關(guān)聯(lián)起來
@ViewChild(‘header’) Header:any;
4、調(diào)用子組件的方法
getChildRun(){ this.Header.run(); }
演示例子:
父組件:home
子組件:header
父組件不僅可以給子組件傳遞簡單的數(shù)據(jù),還可把自己的方法以及整個(gè)父組件傳給子組件
所以在子組件中可以調(diào)用 父組件的方法
1、父組件調(diào)用子組件的時(shí)候傳入數(shù)據(jù)
<app-header [title]="title" [homeWork]="homeWork" [homepage]='this'></app-header>
2、子組件引入 Input 模塊
import { Component, OnInit ,Input } from ‘@angular/core’;
3、子組件中 @Input 接收父組件傳過來的數(shù)據(jù)
export class HeaderComponent implements OnInit { @Input() title:string constructor() { } ngOnInit() {} }
4、子組件中使用父組件的數(shù)據(jù)
這是頭部組件-- {{title}}
5、子組件中使用父組件的方法
總結(jié):
父傳子: @input
子傳父:ViewChild
演示例子:
父組件:news
子組件:footer
1、子組件引入 Output 和 EventEmitter
import { Component, OnInit ,Input,Output,EventEmitter} from ‘@angular/core’;
2、子組件中實(shí)例化 EventEmitter
@Output()
private outer=new EventEmitter();
/用 EventEmitter 和 output 裝飾器配合使用 指定類型變量/
3、子組件通過 EventEmitter 對象 outer 實(shí)例廣播數(shù)據(jù)
sendParent(){ this.outer.emit(‘msg from child’) }
4、父組件調(diào)用子組件的時(shí)候,定義接收事件 ,outer 就是子組件的 EventEmitter 對象 outer
文件:components\news\news.component.html
<app-footer (outer)=“getFooterRun(data)”>
5、父組件接收到數(shù)據(jù)會調(diào)用自己的 getFooterRun 方法,這個(gè)時(shí)候就能拿到子組件的數(shù)
文件:components\news\news.component.ts
//接收子組件傳遞過來的數(shù)據(jù) getFooterRun(data){ console.log(data); }
1、公共的服務(wù)
2、Localstorage(推薦)
3、Cookie
1、父組件可以使用屬性把數(shù)據(jù)傳給子組件,子組件通過props接受。
2、子組件可以使用 $emit 觸發(fā)父組件的自定義事件。
vm.$emit( event, arg ) //觸發(fā)當(dāng)前實(shí)例上的事件 vm.$on( event, fn );//監(jiān)聽event事件后運(yùn)行 fn;
1、父組件可以使用屬性把數(shù)據(jù)傳給子組件,子組件通過@input接受。
2、子組件可以使用 Output 和 EventEmitter 觸發(fā)父組件的自定義事件。
父組件
<app-footer (event)=“getFooterRun(data)”>
子組件
@Output() private event=new EventEmitter<string>(); /*用 EventEmitter 和 output 裝飾器配合使用 <string>指定類型變量*/ sendParent(){ // outer 相當(dāng)于是事件名稱 this.event.emit(data) }
<button (event)=“sendParent()”>通過@Output給父組件廣播數(shù)據(jù)
以上是“Angular中父子組件間如何相互傳參”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。