ng4.x 子組件傳值 / 方法給父組件 -- @Input + @ViewChild

# 1:@Input


步驟:

1:父組件調用子組建時傳方法

2:在子組件引入Input

3:在子組件聲明,通過Input接受父組件傳過來的方法

4:在子組件使用父組件傳過來的數(shù)據(jù)



《parent.component.html》:

<app-child [run] = " run "></app-child>

《child.component.ts》:

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

... ? ...

export class HeaderComponent implement OnInit {

@Input() getDataFromChild;

public childmsg = "這是子組件的數(shù)據(jù)";

constructor() { }

ngOnInit() { }

sendParent(){ ?//子組件自己的方法

? ?this.getDataFromChild(this.childmsg); ?// 子組件調用父組件的方法

}

}

parent.component.ts》:

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

export class NewsComponent implements OnInit {

constructor(){}

... ? ?...

ngOnInit() { ?}

getDataFromChild(childData) {

? ? alert("這是子組件傳來的數(shù)據(jù)"+childData);

}

《child.component.html》:

<button (click) = "sendParent()">給父組件傳值</button>


# 2:過渡 ?-- 父組件調用子組件的方法獲取子組件的值


步驟:

1:父組件調用子組件的時候給子組件起個名字

2:父組件直接可以拿到子組件變量名下的數(shù)據(jù)


《child.component.ts》:

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

... ? ...

export class HeaderComponent implement OnInit {

public msg="這是子組件的數(shù)據(jù)";

constructor() { }

ngOnInit() { }

childFun(){

? alert("這是子組件的方法");

}


《parent.component.html》:

<button (click)="childFun()">調用子組件的方法</button>

<app-child #childCom></app-child>


# 3:@ViewChild ?-- 父組件調用自己的方法獲取子組件的方法和值


步驟:

1:父組件調用子組件的時候給子組件起個名字

2:父組件引入ViewChild

3:ViewChild與子組件關聯(lián)

4:調用子組件

《child.component.ts》:

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

... ? ...

export class HeaderComponent implement OnInit {

public msg="這是子組件的數(shù)據(jù)";

constructor() { }

ngOnInit() { }

childFun(){

alert("這是子組件的方法");

}


《parent.component.html》:

<button (click)="getDataFromChild()">父組件調用自己的方法獲取子組件的數(shù)據(jù)</button>

<app-child #childCom></app-child>

parent.component.ts》:

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

export class NewsComponent implements OnInit {

@ViewChild('childCom') ?cart; ? ? //定義子組件 () 里面和#** 要一致

constructor(){}

... ? ?...

ngOnInit() { ?}

getDataFromChild(childData) {

? ? this.cart.childFun(); ? ? ?//執(zhí)行子組件的方法

? ? alert( this.cart.msg); ? ? //獲取子組件的數(shù)據(jù)

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • # 1: @Input 步驟: 1:父組件調用子組建時傳入值/方法 2:在子組件引入Input模塊 3:在子組件聲...
    __凌閱讀 523評論 0 0
  • Angular 2架構總覽 - 簡書http://www.itdecent.cn/p/aeb11061b82c A...
    葡萄喃喃囈語閱讀 1,547評論 2 13
  • 一、安裝最新版本的 nodejs 注意:請先在終端/控制臺窗口中運行命令 node -v 和 npm -v, 來驗...
    liuguangsen閱讀 2,279評論 0 1
  • 組件基礎 組件用來包裝特定的功能,應用程序的有序運行依賴于組件之間的協(xié)同工作。組件是angular應用的最小邏輯單...
    oWSQo閱讀 1,446評論 0 0
  • 首先吶!先介紹一下尼泊爾! 尼泊爾,全稱尼泊爾聯(lián)邦民主共和國(Federal Democratic Republi...
    JaysonH閱讀 285評論 0 1

友情鏈接更多精彩內容