本文摘自PHP中文网,作者青灯夜游,侵删。
本篇文章给大家介绍一下Angular中父子组件间传值的方法。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。相关推荐:《angular教程》
Angular
中父子组件传值
官方地址:https://angular.cn/guide/component-interaction#component-interaction
1. 父组件给子组件传值
- 说明: 父组件给子组件传值的时候,父组件中在子组件的选择器上绑定数据即可
<app-hero-child [transData]='tran_childData'></app-hero-child>
- 子组件接收的时候需要引入
input
模块import { Component, OnInit, Input} from '@angular/core'
- 子组件还需要使用语法糖的形式接收父组件传递的参数
@input() transData
1.1 父组件hero-parent
1、hero-parent.component.html
1 2 |
|
2、hero-parent.component.ts
1 2 3 4 5 6 7 8 9 10 11 12 |
|
1.2 子组件hero-child
1、hero-child.component.html
1 |
|
2、hero-child.component.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
1.3 效果图
2. 子组件给父组件传递参数
- 说明:子组件给父组件传递参数的时候需要导入
Output
和EventEmitter
,引入模块import { Component, OnInit, Output, EventEmitter} from '@angular/core'
- 使用的时候需要先暴露一个方法
@Output() childEvent = new EventEmitter()
用来使用emit
传递数据 - 具体使用
this.childEvent.emit('我是子组件传递的数据')
2.1 子组件hero-child
hero-child.component.html
1
<button (click)=
'transData_to_parent()'
>我是子组件,给父组件传递参数</button>
hero-child.component.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import { Component, OnInit, Output, EventEmitter} from
'@angular/core'
@Component({
selector:
'app-hero-child'
,
templateUrl:
'./app-hero-child.component.html'
,
styleUrls: [
'./app-hero-child.component.scss'
]
})
export
class
DetailComponent
implements
OnInit {
@Output() childEvent =
new
EventEmitter()
constructor() {}
ngOnInit(): void {},
// 给父组件传递参数
transData_to_parent() {
this.childEvent.emit(
'我是子组件传递的数据'
)
}
}
2.2 父组件hero-parent
1、hero-parent.component.html
1 2 3 |
|
2、hero-parent.component.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
2.3 效果图
更多编程相关知识,请访问:编程视频!!
以上就是详解Angular父子组件间如何传值?的详细内容,更多文章请关注木庄网络博客!
相关阅读 >>
浅谈Angular中的变化检测(change detection)
更多相关阅读请进入《Angular》频道 >>
Vue.js 设计与实现 基于Vue.js 3 深入解析Vue.js 设计细节
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者