父组件传值给子组件
在页面引入input
import { Input } from '@angular/core';
父组件传值给子组件
<app-index [title]="title" [run]="run"></app-index>
子组件使用
@Input() title;
@Input() run;
这样就可以直接使用{{title}},和this.run()在子组件使用父组件的值和方法。
子组件主动发送数据给父组件
引入Output,EventEmitter
import {Output,EventEmitter} from "@angular/core";
在页面使用
@Output() private childOuter = new EventEmitter();
// 子组件主动发送数据
this.childOuter.emit("我是子组件的数据");
在父组件中接收数据
// childOuter即是子组件发送的outer(类似Android中的广播)
<app-index (childOuter)="getData($event)"></app-index>
// ts文件中:
getData(msg:string)
{
console.log(msg);// 接收到的数据
}
父组件主动调用子组件
// 引用子组件
<app-index #index></app-index>
// 使用子组件中的方法
<button (click)="index.childRun()">调用index中的方法</button>
也可以在ts文件中调用:
// 引用子组件 html文件
<app-index #index></app-index>
<button (click)="parentClick(index)">调用index中的方法</button>
// ts 文件
parentClick(obj)
{
obj.childRun();
}
ViewChild主动获取数据
在页面中引入ViewChild
import { ViewChild } from '@angular/core';
@ViewChild("index") index;
// html中引用组件
<app-index #index></app-index>
<button (click)="parentClick()">调用index中的方法</button>
// ts文件中使用子组件的方法和数据
parentChild()
{
this.index.childRun();
}