Angular7父子组件以及父子组件之间的通信 非父子组件之间传值
父组件给子组件传值-@input
public title: string = '我是首页组件的标题';
<app-header [title]="title"></app-header>
import { Component, OnInit, Input } from '@angular/core';
//接受父组件传过来的数据
@Input() title: any;
<header>{{title}}</header>
父组件给子组件传方法
run() {
alert('我是父组件中的一个方法');
}
<button (click)="doFaRun()">子组件执行父组件中的方法</button>
<app-header [run]="run"></app-header>
@Input() run: any;
//执行父组件的方法
doFaRun() {
this.run();
}
将整个父组件传给子组件
@Input() home: any;
<app-header [home]="this"></app-header>
//执行父组件的方法
doFaRun() {
alert(this.home.msg);
this.home.run();
}
子组件给子父组件传值
public msg: string = "我是子组件的一个msg";
run() {
alert("我是子组件的一个方法");
}
<app-footer #footer></app-footer>
- 在父组件中写两个按钮,并在父组件ts文件中实例化这两个方法
<button (click)="getChildMsg()">
获取子组件定义的msg
</button>
<br>
<br>
<button (click)="doChildRun()">
执行子组件定义的方法
</button>
//获取子组件定义的msg
getChildMsg() {
}
//执行子组件定义的方法
doChildRun() {
}
- 在父组件ts文件中引入viewChild
import { ViewChild } from '@angular/core';
- 在父组件html中获取到子组件
@ViewChild("footer") footer: any;
//获取子组件定义的msg,执行子组件中的方法
getChildMsg() {
alert(this.footer.msg);
}
//执行子组件定义的方法
doChildRun() {
this.footer.run();
}
小结:父子组件之间传值,就直接将整个组件传过去,然后通过组件获取值或者调用方法。
非父子组件之间传值就用service传值