Angular 父子組件以及組件之間通訊


 

 

 一、 父組件給子組件傳值-@input

例如 根組件是

home是父組件

header是子組件

在home.component.html引入子組件:<header

1. 父組件調用子組件的時候傳入數據

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

在父組件中定義數據

public msg:string="首頁組件的標題"

 

2. 子組件引入 Input 模塊

header.component.ts引入:

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

3. 中 子組件中 @Input 接收父組件傳過來的數據

export class HeaderComponent implements OnInit {

//接受父組件傳來的數據
@Input() msg:string

 

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

header.component.html:

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

二、 子組件通過@Output 觸發父組件的方

(1)在父組件home.component.ts中定義方法

例如

run(){

alert"我是父組件的run方法")

}

 

(2)在父組件中home.component.html中引入子組件

<app-header [run]='run'></app-header>

(3)在子組件header.component.ts

@input() run:any

 

 把父組件整個實例傳給子組件,子組件可以調用父組件的數據和方法

 

1.在父組件中home.component.html中引入子組件

<app-header [home]='this'></app-header>

【home】中home為自定義

2.在子組件header.component.ts

@Input() home:any;

 

 

三、 父組件通過@ViewChild 主動獲取子組
件的數據和方法

例如

父組件:new

子組件:footer

1.在父組件中new.component.html中引入子組件

定義子組件名稱

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

2.子組件footer.component.ts定義數據和方法

 3.父組件中html中

<button (click)='getchildMSg()'>獲取子組件的msg</button>

<button (click)='getchildrun()'>執行子組件的run</button>

4.在父組件ts中,引入ViewChild,button中的定義方法

 非父子組件之間傳值和共享方法

1.服務可以實現

2.Loclstorage

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM