angular父子組件的傳值,兄弟之間傳值


1.父級向子級傳值,不管是屬性,方法,還是整個父級對象this,都可以通過類似變量的形式傳入,具體如下

<app-detail #detail msg="123"></app-detail> //傳入的值不是變量
<app-detail #detail [msg]="parentMsg"></app-detail> //傳入的是變量
 
import { Component, OnInit, Input } from '@angular/core';
 
// 通過input裝飾器獲取父級傳過來的值
 
@Input() msg: string;  //獲取值
 
ngOnInit() {
 
  console.log(this.msg, '-----子組件傳過來的msg-----');
 
}
 
//直接 this 可以引用

2.父級獲取子組件的信息

第一種可以通過ViewChild的方式進行獲取

<app-detail #detail [msg]="parentMsg"></app-detail>  //組件
import { Component, OnInit, AfterViewInit, ViewChild } from '@angular/core';
//引入 ViewChild
@ViewChild('detail') myDom: any;
ngAfterViewInit(): void {
   console.log(this.myDom.msg);
   this.myDom.run();
}
//直接就能獲取子組件的數據

第二種通過@Output 和 EventEmitter獲取

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
 
//子組件引入裝飾器
 
@Output() private outer = new EventEmitter();
 
//定義@Output的裝飾器
 
emitData() {
 
    this.outer.emit('傳入給父級的值');
 
}
 
//子組件emit給父級的方法
 
<button (click)="emitData()">提交數據給父級</button> //按鈕觸發
<app-detail #detail [msg]="parentMsg" (outer)="getChildMsg($event)"></app-detail>
 
//父級通過outer事件接受,參數是$event, outer必須和子組件定義的變量名一致
 
getChildMsg(msg) {
 
  console.log(msg, '---從子集拿過來的值---');
 
}
 
// 父級獲取emit傳過來的值

3.兄弟之間傳值通過localStorage或者是服務進行獲取

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM