角父子组件间怎么传值

  介绍

小编给大家分享一下角父子组件间怎么传值,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获、下面让我们一起去了解一下吧!

<强> <代码>角>

官方地址:https://angular.cn/guide/component-interaction组件交互

<强> 1。父组件给子组件传值

<李>

说明:父组件给子组件传值的时候,父组件中在子组件的选择器上绑定数据即可<代码> & lt; app-hero-child [transData]=& # 39; tran_childData& # 39;祝辞& lt;/app-hero-child>

<李>

子组件接收的时候需要引入输入<代码> 模块<代码>{进口组件,> & lt; p>这是父组件& lt;/p>   & lt; app-hero-child  [transData]=& # 39; tran_childData& # 39;祝辞& lt;/app-hero-child>

2, hero-parent.component.ts

import {组件的不同之处是,OnInit },得到& # 39;@angular/核心# 39;      @ component ({   ,,,选择器:,& # 39;app-hero-parent& # 39;   ,,,templateUrl:, & # 39;。/app-hero-parent.component.html& # 39;   ,,,styleUrls:, (& # 39;。/app-hero-parent.component.scss& # 39;】   })   export  class  HeroesComponent  implements  OnInit  {   ,,,tran_childData: string =, & # 39;这是父组件传递给子组件的数据& # 39;   ,,,构造函数(),{}   ,,,ngOnInit ():, void  {}   } 1.2子组件<代码> hero-child

1, hero-child.component.html

& lt; p> {{transData}} & lt;/p>

2, hero-child.component.ts

import {,组件,OnInit,输入},得到& # 39;@angular/核心# 39;      @ component ({   ,,,选择器:,& # 39;app-hero-child& # 39;   ,,,templateUrl:, & # 39;。/app-hero-child.component.html& # 39;   ,,,styleUrls:, (& # 39;。/app-hero-child.component.scss& # 39;】   })   export  class  DetailComponent  implements  OnInit  {   ,,,@Input (), transData:字符串   ,,,构造函数(),{}   ,,,ngOnInit ():, void  {   ,,,,,,,console.log (this.transData)   ,,,}   } 1.3效果图

角父子组件间怎么传值

<强> 2。子组件给父组件传递参数

<李>

说明:子组件给父组件传递参数的时候需要导入输出<代码> 和<代码> EventEmitter> {进口组件,> <李>

<代码> hero-child.component.html

& lt; button (点击)=& # 39;transData_to_parent() & # 39;在我是子组件,给父组件传递参数& lt;/button> <李>

<代码> hero-child.component.ts

import {,组件,OnInit,输出,EventEmitter},得到& # 39;@angular/核心# 39;      @ component ({   ,,,选择器:,& # 39;app-hero-child& # 39;   ,,,templateUrl:, & # 39;。/app-hero-child.component.html& # 39;   ,,,styleUrls:, (& # 39;。/app-hero-child.component.scss& # 39;】   })   export  class  DetailComponent  implements  OnInit  {   ,,,@Output (), childEvent =, new  EventEmitter ()   ,,,构造函数(),{}   ,,,ngOnInit ():, void  {},   ,,,//,给父组件传递参数   ,,,transData_to_parent (), {   ,,,,,,,this.childEvent.emit(& # 39;我是子组件传递的数据& # 39;)   ,,,}   李}

<强> 2.2父组件<代码> hero-parent

1, hero-parent.component.html

& lt; p>这是父组件& lt;/p>   & lt; p> {{receiceData}} & lt;/p>   & lt; app-hero-child  (childEvent)=& # 39; receive_child_data事件($)& # 39;祝辞& lt;/app-hero-child>

2, hero-parent.component.ts

import {组件的不同之处是,OnInit },得到& # 39;@angular/核心# 39;      @ component ({   ,,,选择器:,& # 39;app-hero-parent& # 39;   ,,,templateUrl:, & # 39;。/app-hero-parent.component.html& # 39;   ,,,styleUrls:, (& # 39;。/app-hero-parent.component.scss& # 39;】   })   export  class  HeroesComponent  implements  OnInit  {   ,,,构造函数(),{}   ,,,ngOnInit ():, void  {}   ,,,receiceData:字符串   ,,,//,接收子组件传递的数据   ,,,receive_child_data(数据),{   ,,,,,,,this.receiceData =数据   ,,,}   }

<强> 2.3效果图

角父子组件间怎么传值