angular中父子元件傳值(一)
阿新 • • 發佈:2018-11-09
子元件使用父元件的方法變數
- 使用ng g component 元件名稱下載兩個元件
ng g component components/father ng g component components/son
-
在根元件app.module.ts中引入父子元件並宣告
import { FatherComponent } from './components/father/father.component'; import { SonComponent } from './components/son/son.component'; declarations: [ AppComponent, NewsComponent, FatherComponent, SonComponent ]
-
在根元件中使用父元件
<app-father></app-father>
-
父元件中使用子元件並把方法和變數傳給子元件
<app-son [msg]="msg" [run]="run" [getDataFromChild]="getDataFromChild"> <!--把父元件中的meg資訊流向子元件 []中的為方法名或值 可以自定義 ""號中的為 --> </app-son>
父元件中宣告方法和變數
public msg = "我是父元件的資訊"; run(){ alert("這是父元件的方法!!!") } getDataFromChild(childData){ alert(childData); }
-
子元件中引入Input
import { Component, OnInit,Input } from '@angular/core';
子元件獲取父元件的方法和變數
@Input() msg:String; @Input() run:any; @Input() getDataFromChild;
子元件中使用父元件的方法和變數
<h2> {{msg}}</h2> <button (click)="run()">方法</button>
父元件獲取子元件的變數
1.子元件宣告自己的變數方法
通過呼叫自己的方法使用父元件傳過來的方法傳遞自己的資訊
public sonMsg = "子元件的資訊傳遞!!!!"
doPost(){
this.getDataFromChild(this.sonMsg);
}