1父组件向子组件传值
子组件内容
import { Component, Input, OnInit } from '@angular/core';
@Input() msg;
父组件内容
msg="新闻栏目"
<app-home [msg]="msg"></app-home>
<div>{{msg}}</div>
2子组件向父组件传值
子组件向父组件传值,需要触发事件才可以,所以需要在子组件里写一个传值事件,然后再写个按钮触发,同时在子组件是ts文件里引入 Output,EventEmitter
并且在类里面实例化,其中outer自己可以随便写,但要保持一致,还需要用到emit()
父组件要做的工作有:
在父组件的子组件元素上接收子组件暴露的值,在方法里要用到$event
,在父组件的ts文件里面写一个接收的方法,再定义一个接收值的变量,最后在父组件HTML文件里面显示出来就ok了
子组件内容
import { Component, Output,EventEmitter, OnInit } from '@angular/core';
@Output() outer = new EventEmitter();
send(){
this.outer.emit('好好学习天天向上');
}
<button (click)="send()">点击过去</button>
父组件内容
<app-home [msg]="msg" (outer)="getMsg($event)"></app-home>
info1="";
getMsg(info:string){
this.info1=`从组件中获取的值:${info}`
console.log(this.info1)
}
<h1>{{info1}}</h1>
首先我们需要用到父组件HTML,父组件ts,子组件HTML,子组件ts
四个文件
父组件HTML
<h1>{{info1}}</h1>
<app-home [msg]="msg" (outer)="getMsg($event)"></app-home>
父组件ts文件
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
msg="新闻栏目";
info1="";
getMsg(info:string){
this.info1=`从组件中获取的值:${info}`
console.log(this.info1)
};
}
子组件HTML文件
<button (click)="send()">点击过去</button>
<div>{{msg}}</div>
子组件ts文件
import { Component,Input, Output,EventEmitter, OnInit } from '@angular/core';
// input修饰器
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
@Input() msg:any;//any表示接收任何类型的值
@Output() outer = new EventEmitter();
constructor() { }// 构造函数 不做业务逻辑,只用于依赖注入
ngOnInit(): void {// 生命周期函数,写业务逻辑
}
send(){
this.outer.emit('好好学习天天向上');
}
}