Angular中父子组件传值@Input @Output @ViewChild最全面最简单的总结
生活随笔
收集整理的這篇文章主要介紹了
Angular中父子组件传值@Input @Output @ViewChild最全面最简单的总结
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
父組件傳遞給子組件:
值傳遞方式:@Input既可以傳遞數(shù)據(jù)也可以傳遞方法
- 傳遞數(shù)據(jù)(不舉例了)
- 傳遞方法
調(diào)用子組件時傳入當(dāng)前方法(是傳遞方法不是調(diào)用方法)
<app-header [msg]="msg" [run]="parentRun"></app-header>子組件接收和使用父組件傳過來的方法
import { Component, OnInit ,Input } from '@angular/core';export class HeaderComponent implements OnInit {@Input() msg:string @Input() run:any; // 接收父組件傳遞過來的方法parentRunconstructor() { } ngOnInit() {this.run(); // 子組件調(diào)用父組件的parentRun方法}}子組件傳遞給父組件:
1、事件傳遞方式:@Output + EventEmitter事件傳遞的方式
子組件實例化裝飾器修飾的EventEmitter實例,并在需要的時候發(fā)出傳遞事件的信號(可以傳參)
import { Component, OnInit ,Input,Output,EventEmitter} from '@angular/core';export class HeaderComponent implements OnInit {// 用EventEmitter和Output裝飾器配合使用,<string>指定廣播傳遞的參數(shù)類型變量@Output() private outer = new EventEmitter<string>(); sendParent(){this.outer.emit('msg from child'); // 廣播傳遞數(shù)據(jù)給父組件}}父組件調(diào)用子組件的時候,定義接收事件 , outer就是子組件的EventEmitter對象outer
<!--一旦接收到子組件發(fā)出的事件傳遞信號后就會執(zhí)行父組件中定義好的接收方法--> <app-header (outer)="runParent($event)"></app-header> // 接收子組件傳遞過來的數(shù)據(jù) runParent(msg:string){alert(msg); }2、主動獲取:父組件通過局部變量獲取子組件的引用,主動獲取子組件的數(shù)據(jù)和方法
子組件定義如下:
export class FooterComponent implements OnInit { public msg:string;public msg: string;constructor() { } ngOnInit() {} footerRun(){alert('這是footer子組件的Run方法');} }父組件調(diào)用子組件的時候給子組件取個id標識
<app-footer #footer></app-footer>2.1、可在頁面上直接獲取執(zhí)行子組件的方法
<button (click)='footer.footerRun()'>獲取子組件的數(shù)據(jù)</button>2.2、在控制器controller中通過@ViewChild,引入為成員變量
import { Component, OnInit ,ViewChild} from '@angular/core';@ViewChild('footer') footerChild; // 在父組件的控制器中引用子組件run(){this.footerChild.footerRun(); // 在父組件的控制器中調(diào)用子組件的方法或變量}?
?
?
?
?
?
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎總結(jié)
以上是生活随笔為你收集整理的Angular中父子组件传值@Input @Output @ViewChild最全面最简单的总结的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: isstart.exe是什么进程 iss
- 下一篇: 视觉SLAM十四讲(3):三维空间刚体运