1使用@input传递数据
1、父组件使用自组件app-header传入msg数据。
<app-header [msg]="msg"></app-header>
2、子组件引入 Input
import { Component, OnInit ,Input } from '@angular/core';
3、子组件中 @Input msg:string 接收父组件传过来的数据
export class HeaderComponent implements OnInit {
@Input() msg:string
constructor() { }
ngOnInit() {
}
}
4、子组件使用父组件的数据
{{msg}}
2使用@input传递数据
实现子组件调用父组件的方法
1、父组件定义方法
run(){
alert('这是父组件的 run 方法');
}
2、在使用自组件是传递方法 run()
<app-header [msg]="msg" [run]="run"></app-header>
3、子组件接收父组件的方法并使用过
export class HeaderComponent implements OnInit {
@Input() msg:string;
@Input() run:any;
constructor() { }
ngOnInit() {
this.run(); /*子组件调用父组件的 run 方法*/
}
}