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