angular的組件傳值


angular組件傳值存在三種情況,分別是父傳子 ,子傳父,以及非父子之間進行傳值

1.父傳子

通過在子組件上綁定屬性或者方法,在子組件xxx.componet.ts中 導入Input類, 進行接收,可以獲取父組件傳過來的內容

父組件.html

<app-home [msg] = 'msg' [run]='logApp' [home]='this'></app-home>
// msg是數據  logApp是方法名   this是這個組件的對象

 

子組件.component.ts

import {Input} from '@angular/core';
---------------------------------------------------
@input() msg:string;
@input() run:any;
@input() home:home;
// 使用的時候用this進行調用

  

2.子傳父

1.Output & eventEmitter

通過引入Output 和eventEmitter 可以設置自定義事件 從而使父組件

第一步 在子組件中引入Output 以及 eventEmitter

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

 

第二步

@Output private outer = new EventEmitter()

 

第三步,定義一個方法 在方法中通過emit 調用父組件的方法

setData(){
    this.outer.emit('是嘛')
  }

 

第四步, 在父組件中的標簽上設置事件

// html
<app-foot (outer)="getData($event)"></app-foot>
// ts
getData(msg:string){
    console.log(msg);
  }

 

注意點: 在父組件.html中綁定方法的時候 方法名必須和子組件.component.ts中 通過 new eventEmitter()實例出的對象一致, 不然就會出現錯誤

2.viewChild

在父組件.html 給子組件標簽綁定上 #xxx 通過@viewChild 獲取子組件的對象 就可以獲取子組件的數據以及調用子組件的方法

// .html  綁定#xxx屬性
<app-news #newsChild></app-news>
// component.ts
import { ViewChild } from '@angular/core';
​
-----------------------
// 獲取到news對象 就是組件
@viewChild('newsChild') news
​

 


在方法中 this.news就是可以獲取這個對象實例

3.非父子之間的傳值

1.service 通過服務可以進行傳值

2.本地存儲 localStorage sessionStorage

 


免責聲明!

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



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