【Angular】父子组件传值

父传子

1.父组件引用子组件,并绑定需要传的值或者方法

<!-- 父组件调用子组件 -->
<app-son [id]="id" [run]="run"></app-son>

2.子组件接收

import { Component, OnInit, Input } from '@angular/core';

@Input() id:any; // 接收值
@Input() run:any; // 接收方法

this.run(); //可直接使用方法
doSubmit(){
	console.log(this.id); // 也可直接使用值
}

子传父

1.父组件引用子组件

<!-- 父组件调用子组件 -->
<app-son #son (outer)="run($event)"></app-son>
<!-- 定义获取子组件信息的方法 -->
<button (click)="getChildMsg()">获取子msg</button>
<button (click)="getChildFunc()">获取子方法</button>

2.父组件在ts中获取子组件的实例

import { Component, OnInit, Input, ViewChild } from '@angular/core';

//根据ViewChild获取子组件实例
@ViewChild('son') son:any;

//调用方法,可获取子组件的数据及方法
getChildMsg(){
   console.log(this.son.msg);
}
getChildFunc(){
   this.son.run();
}

3.子组件通过广播的形式,向父组件发送数据

//子组件引用Output, EventEmitter
import { Component, OnInit, Output, EventEmitter } from '@angular/core';

//获取引用实例
@Output() private outer = new EventEmitter();

//定义方法向父组件传值
setParent(){
    //向父组件传值
    this.outer.emit("我是子组件的数据")
}

4.父组件接收

在html中绑定了(outer)="run($event)"后,在父组件的ts文件中:

// 子组件广播时触发父组件方法,
run(event:any){
    console.log(event);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

知野小兔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值