Angular -- 組件傳值


一、父傳子

  1. 在父組件ts中定義要傳遞的信息

  2. 在父組件html中的子組件標簽中定義自定義屬性來綁定父組件定義的信息


  3. 在子組件中的ts中,通過@Input來接收自定義屬性的名稱

    import {Input} from '@angular/core';

    @Input() info:string;

  4. 在子組件中的html中就能直接得到值了

    {{info}} ===> father to child

 

二、子傳父

  方法一:@Output

  1. 在子組件中導入Output 和 EventEmitter

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

  2. 並且通過@Output實例化要傳遞向父組件的消息

    @Output() private outer = new EventEmitter();

    public chtofather = 'child to father';

  3. 給子組件添加點擊事件,點擊的時候將數據傳遞給父組件

    handlerClick() {

    this.outer.emit(this.chtofather)

    }

    <p (click)="handlerClick()"></p>
  4. 在父組件html中綁定自定義事件

    <app-test (outer) = "handlerChild($event)"></app-test>

  5. 在父組件的ts中通過剛剛綁定的自定義事件中的event就可以獲取到了

    handlerChild(e) {

    console.log(e)

    }

  方法二:@ViewChild

  1. 在父組件html里的子組件標簽上定義一個名字(#名字),相當於這個子組件的id名

    <app-son #son ></app-son>    
  2. 在父組件的ts中引入ViewChild

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

  3. 並使用

    @ViewChild('son') son; 括號里面的名稱要與子組件標簽#后面的名稱一致。

  4. 最后就可以調用子組件的數據和方法,如果子組件中有一個數據為viewChildinfo,就可以這樣去調用

    getData() {

    this.mydata = this.son.viewChildinfo;

    }


免責聲明!

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



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