父传子
- 在子组件的ts文件中导入input
import { Component, OnInit, Input} from '@angular/core';
- 在export中定义
export class ChildComponent implements OnInit {
@Input() item;
}
- 父组件的HTML文件中
<app-child [item]="sendchildMsg"> </app-child>
- 父组件的ts文件中赋值
sendchildMsg = '李';
- 子组件HTML文件中展示
{{item}}
需要注意的是:
@Input() item; 后的item变量名必须和<app-child [item]=“sendchildMsg”> 一样
子传父
1.在子组件的ts文件中导入 output eventemitter
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
2.在export中定义
export class ChildComponent implements OnInit {
@Output() parmsg = new EventEmitter();
}
3.子组件HTML文件中定义一个方法
<button (click)="sendMsg()">发送消息给父组件</button><br>
4.实现方法
sendMsg() {
this.parmsg.emit({ msg: "我子组件,这是我发给父组件的消息" })
}
5.父组件接收
<app-child (childMsg)="getEvent($event)"></app-child><br>
子组件发来信息:{{sss}}
- 父组件中定义方法
sss = "";
getEvent(event) {
console.log(event)
this.sss = event.msg;
}