小編給大家分享一下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
<p>這是父組件</p> <app-hero-child [transData]='tran_childData'></app-hero-child>
2、hero-parent.component.ts
import { Component, OnInit } from '@angular/core' @Component({ selector: 'app-hero-parent', templateUrl: './app-hero-parent.component.html', styleUrls: ['./app-hero-parent.component.scss'] }) export class HeroesComponent implements OnInit { tran_childData:string = '這是父組件傳遞給子組件的數據' constructor() {} ngOnInit(): void {} }
hero-child
1、hero-child.component.html
<p>{{transData}}</p>
2、hero-child.component.ts
import { Component, OnInit, Input} 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 { @Input() transData: string constructor() {} ngOnInit(): void { console.log(this.transData) } }
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
<button (click)='transData_to_parent()'>我是子組件,給父組件傳遞參數</button>
hero-child.component.ts
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
<p>這是父組件</p> <p>{{receiceData}}</p> <app-hero-child (childEvent)='receive_child_data($event)'></app-hero-child>
2、hero-parent.component.ts
import { Component, OnInit } from '@angular/core' @Component({ selector: 'app-hero-parent', templateUrl: './app-hero-parent.component.html', styleUrls: ['./app-hero-parent.component.scss'] }) export class HeroesComponent implements OnInit { constructor() {} ngOnInit(): void {} receiceData:string // 接收子組件傳遞的數據 receive_child_data(data) { this.receiceData = data } }
2.3 效果圖
以上是“Angular父子組件間怎么傳值”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。