父子组件传值
1.父向子传值(input传入)
父组件
<hr>
<button (click)="toSon()">点击一下给子组件传值</button>
<app-son [msg]="msg" ></app-son>
export class AppComponent {
num = 'yyu';
msg = '' ;// 要传给子组件的值
toSon():void {
this.msg = this.num
}
}
子组件
import { Component ,OnInit,Input} from '@angular/core';
@Component({
selector: 'app-son',
template: `<hr> <h2>{{msg}}</h2>`,
styleUrls: [],
})
export class SonComponent implements OnInit {
@Input() msg;
ngOnInit(): void {
}
}
2.子向父传值(Output传入)
子组件
import { Component ,OnInit,Output,EventEmitter} from '@angular/core';
@Component({
selector: 'app-son',
template: `<hr >,
<button (click)="toFather()">点击一下给父组件传值</button>`,
styleUrls: [],
})
export class SonComponent implements OnInit {
data = '这是给父组件的数据';
msg = '' ; //给父组件的信息
@Output() getMsg = new EventEmitter()
ngOnInit(): void {
}
toFather(): void {
this.msg = this.data
this.getMsg.emit(this.msg)
}
}
父组件
<hr>
<h1>子组件传递过来的值:{{msgFa}}</h1>
<app-son (getMsg)="getMsg($event)" ></app-son>
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
msgFa = '';
getMsg(data):void {
this.msgFa= data
}
}