Angular父子组件通信

本文详细介绍了Angular中父子组件之间的通信方法,包括从父组件向子组件传递数据的@input和inputs方式,以及子组件向父组件传递数据的ViewChild、Output和EventEmitter的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

父传子

1.使用@input方式传值

@Input('xxx') 可以接收一个参数用于父组件传值时 [ ] 的名称
1. 在子组件的component.ts中导入Input并声明该变量
1.1 `import {Input} from '@angular/core`
1.2 在构造函数中 @Input() xxx:any;  //any可以换成别的类型
	
2. 在父组件中使用子组件时 如 <app-son [xxx]='fatherData'></app-son>  
	其中app-son是子组件 fatherData是父组件components中的变量 
		
3. xxx使用和子组件中变量的使用没什么区别

2.使用inputs方式传值

1.在子组件component.ts中
@component({
	inputs:['xxx']    //input是用来接收父组件传递的值
})
2.父组件使用子组件时 <app-son [xxx]='fatherData'></app-son>
fatherData是父组件中的变量 不能直接写字符串
3. this.xxx即可正常使用

子传父

1.使用ViewChild

1. 给子组件添加标记
<app-son #son></app-son>
2. 导入ViewChild
import { ViewChild } from '@angular/core';
3. @ViewChild('son',{static:true}) son:any;
4. 可以在html中直接使用 son.methodName 的方式调用子组件中的方法
5. 需要注意的是 son只能在ngAfterViewInit()这个生命周期开始才能使用 只有当页面初始化完成之后 才可以拿到这个子组件

2.使用Output和EventEmitter

1.导入Output和EventEmitter
import { Output,EventEmitter } from ‘@angular/core’;
2.在子组件类中创建事件 在生命周期函数中发送事件
不要写在contructor里面 
@Output() 接收一个参数 用于父组件调用时 ( ) 中的名称
@Output() sonEvent=new EventEmitter();
ngOnInit(){
	this.sonEvent.emit('data');
}
3.当子组件事件触发时 父组件使用方法接收 必须使用参数 $event接收数据
<app-son (sonEvent)="getSonData($event)"></app-son >
   // 父组件的方法 
   getSonData(event:any){
		console.log(event);
   }

3.使用outputs

1.在子组件中
@Component({
		outputs:['sonEvent']
})
2.在类中定义子组件的事件
public sonEvent:EventEmitter<any>;
3. 在子组件的构造函数中初始化事件
this.sonEvent=new EventEmitter();
4.在需要发送的时候发送事件
this.sonEvent.emit('data');
5.当子组件事件触发时 父组件使用方法接收 必须使用参数 $event接收数据
<app-son (sonEvent)="getSonData($event)"></app-son >
父组件的方法 
getSonData(event:any){
	console.log(event);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值