本篇文章為大家介紹一下Angular中父子元件間傳值的方法。有一定的參考價值,有需要的朋友可以參考一下,希望對大家有幫助。
相關推薦:《angular教學》
<span style="font-size: 20px;">Angular</span>
##中父子元件傳值
官方位址:https://angular.cn/guide/component-interaction#component-interaction
子元件接收的時候需要引入 input
import { Component, OnInit, Input} from '@angular/core'
子元件也需要使用語法糖的形式接收父元件傳遞的參數
hero-parent
1、hero-parent.component.html
<p>这是父组件</p> <app-hero-child></app-hero-child>
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 {} }
<p>{{transData}}</p>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">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)
}
}</pre><div class="contentsignin">登入後複製</div></div>
1.3 效果圖
#2.子元件給父元件傳遞參數
Output
和import { Component, OnInit, Output, EventEmitter} from '@angular/core'使用的時候需要先暴露一個方法@Output() childEvent = new EventEmitter ()
具體使用
hero-child
#hero-child.component.html
<button>我是子组件,给父组件传递参数</button>
hero-child.component.tsimport { 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></app-hero-child>
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 } }
以上是詳解Angular父子組件間如何傳值?的詳細內容。更多資訊請關注PHP中文網其他相關文章!