一:父传子
子组件可以获取父组件的数据
子组件可以执行父组件的方法
子组件通过@Input装饰器进行接收父组件传过来的值
父组件
export class AppComponent {
public title = '父组件';
run(){
alert('父组件方法')
}
}
//在父组件中引入子组件并且以变量的形式给子组件传值
<app-children [title]="title" [run]="run"></app-children>
子组件引入Input
import { Component, OnInit, Input } from '@angular/core';
export class ChildrenComponent implements OnInit {
//通过@Input 接收父组件传过来的值
@Input() title : any;
@Input() run : any;
constructor() { }
ngOnInit(): void {
}
// 获取父组件的方法
getRun(){
this.run()
}
}
//子组件直接通过模板变量使用即可
<p>{{title}}</p>
<p (click)="getRun()">接收父组件的自定义方法</p>
也可以把整个父组件传递给子组件:
eg:在子组件上挂载父组件 [home] = 'this' this指的就是整个父组件, 在子组件上接收 首先定义一个初始值,然后在掉用父组件的方法/值 this.home.run()/this.home.title
二:子传父
父组件可以获取子组件的数据
父组件可以获取子组件的方法
①:子组件可以通过@Output装饰器和EventEmitter触发父组件的方法
子组件
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
/** 子传父 通过@Output() 装饰器传递
private 定义私有化变量
new EvenrEmitter 实例
*/
@Output() private outer = new EventEmitter<string>();
// 传递数据
outMsg(){
// alert('chuandishuju')
this.outer.emit(this.msg)
}
<button (click)="outMsg()">子组件通过@Output给父组件传递数据</button>
父组件
<app-children (outer)="recive($event)"> </app-children>
//获取子组件传递过来的数据
recive(e:any){
alert(e)
}
②:父组件通过@ViewChild 主动获取子组件的数据和方法,通过事件进行获取
子组件
public msg ='我是子组件的msg'
父组件
<app-children #footer></app-children>
//通过事件主动获取子组件的数据
<button (click)="getMsg()">获取子组件的msg</button>
//引入ViewChild
import { Component,ViewChild } from '@angular/core';
@ViewChild('footer') footer:any;
getMsg(){
alert(this.footer.msg)
}
三:非父子组件
组件之间互相传值
共享方法