- 页面调用组件 的时候传入数据
<app-header [msg]="msg"></app-header>
- 组件引入 Input 模块,接收页面传过来的数据
import { Component, OnInit ,Input } from '@angular/core';
export class HeaderComponent implements OnInit {
@Input() msg:string
}
- 页面定义方法
run(){
alert('这是页面的 run 方法');
}
- 组件传入方法
<app-header [msg]="msg" [run]="run"></app-header>
- 组件接收传过来的方法
import { Component, OnInit ,Input } from '@angular/core';
export class HeaderComponent implements OnInit {
@Input() run:any;
ngOnInit() {
this.run(); /*组件调用页面的 run 方法*/
}
}
- 组件引入 Output 和 EventEmitter
import { Component, OnInit ,Input,Output,EventEmitter} from '@angular/core';
- 组件中实例化 EventEmitter
@Output() outer=new EventEmitter<string>();/*用EventEmitter和output装饰器配合使用 <string>指定类型变量*/
- 组件通过 outer 实例广播数据
sendParent(){// alert('zhixing');
this.outer.emit('msg from child')
}
- 页面调用组件的时候,定义接收事件 , outer 就是组件的 EventEmitter 对象 outer
<app-header (outer)="runParent($event)"></app-header>
- 页面接收到数据会调用自己的 runParent 方法
runParent(msg:string){ //接收组件传递过来的数据
alert(msg);
}
-
页面通过局部变量获取组件的引 用 ,主动获取组件的数据和方法(一)
- 定义footer组件
footerRun(){
alert('这是 footer 子组件的 Run 方法');
}
- 页面调用组件的时候给组件起个名字
<app-footer #footer></app-footer>
- 直接获取组件的方法
<button (click)='footer.footerRun()'>获取子组件的方法</button>
-
页面通过局部变量获取组件的引 用,通过 ViewChild 主动获取组件的数据和方法
- 调用组件给组件定义一个名称
<app-footer #footerChild></app-footer>
- 引入 ViewChild
import { Component, OnInit ,ViewChild} from '@angular/core';
@ViewChild('footerChild') footer;
- 组件中定义一个数据
public msg="this is child data";
- 页面调用自己的方法获得组件的方法或数据
run(){
this.footer.footerRun(); //页面执行组件的方法
alert(this.footer.msg); //页面获取组件的数据
}