# 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);
})
}
}