# 1: @Input
步驟:
1:父組件調用子組建時傳入值/方法
2:在子組件引入Input模塊
3:在子組件聲明,通過@Input接受父組件傳過來的數據/方法
4:在子組件使用父組件傳過來的數據/方法
《parent.component.html》:【父】
<app-child ? ? [msg] = "msg" [run] ="run"></app-child>
《child.component.ts》:【子】
import { Component, OnInit, Input } from '@angular/core'; ? //?
... ? ...
export class HeaderComponent implement OnInit {
@Input() msg:string;
@Input() run;
constructor() { }
ngOnInit() { }
}
《parent.component.ts》:
import { Component, OnInit }from '@angular/core';
export class NewsComponent implements OnInit {
public msg = "這是父組件的數據";
constructor(){}
... ? ?...
run() {
? alert("這是父組件的方法");
}
}
《child.component.html》:
<h2> ?這是父組件傳來的值: {{ msg }}</h2>
<button (click)="run()">接受父組件傳來的方法</button>
# 2: @Output
步驟:
1:子組件引入Output 和 EventEmitter
2:子組件中實例化 EventEmitter
3:子組件通過EventEmitter對象outer實例廣播數據
4:父組件調用子組件的時候,定義接受事件
《parent.component.html》:
<app-child (toparent)="resuestData($event)"></app-child>
《child.component.html》:
<button (click) = "requersData()">執行父組件的方法 通過@Output</button>
《child.component.ts》:
import { Component, OnInit, Input, Output, EventEmitter} from '@angular/core'; ??
... ? ...
export class HeaderComponent implement OnInit {
@Input() msg:string;
@Input() run;
@Output() private toparent = new EventEmitter<string>();
constructor() { }
ngOnInit() { }
requestData(){
? ? ?this.toparent.emit('這是子組件傳的值');
}
}
《parent.component.ts》:
export class NewsComponent implements OnInit {
public msg = "這是父組件的數據";
public list = [];
constructor(private http:Http){ ?}
... ? ?...
requestData(e){
console.log(e);
var _that=this;
var url ="***";
this.http.get(url).map(res=>res.json()).subscribe(function(data){
console.log(data);
},function(err){
console.log(err);
})
}
}