目錄
1. 父元件透過屬性傳遞值給子元件
2. 子元件透過Emitter 事件傳遞訊息給父元件
3. 透過引用,父元件取得子元件的屬性與方法
4.透過service 去變動
首頁 web前端 js教程 帶你了解Angular組件間進行通訊的幾種方法

帶你了解Angular組件間進行通訊的幾種方法

Dec 26, 2022 pm 07:51 PM
angular 組件通信

Angular元件間怎麼通訊?以下這篇文章帶大家了解Angular中元件通訊的方法,希望對大家有幫助!

帶你了解Angular組件間進行通訊的幾種方法

上一篇,我們講了 Angular 結合 NG-ZORRO 快速開發。前端開發,很大程度是組件化開發,永遠遠離不開組件之間的通訊。那麼,在 Angular 開發中,其元件之間的通訊是怎麼樣的呢? 【相關教學推薦:《angular教學》】

舉一反三,VueReact 中大同小異

#本文純文字,比較枯燥。因為控制台列印的東西比較雞肋,所以就不配圖了,嗯~希望讀者跟著說明程式碼走一遍更容易吸收~

1. 父元件透過屬性傳遞值給子元件

相當於你自訂了一個屬性,透過元件的引入,將值傳遞給子元件。 Show you the CODE

<!-- parent.component.html -->

<app-child [parentProp]="&#39;My kid.&#39;"></app-child>
登入後複製

在父元件中呼叫子元件,這裡命名一個 parentProp 的屬性。

// child.component.ts

import { Component, OnInit, Input } from &#39;@angular/core&#39;;

@Component({
  selector: &#39;app-child&#39;,
  templateUrl: &#39;./child.component.html&#39;,
  styleUrls: [&#39;./child.component.scss&#39;]
})
export class ChildComponent implements OnInit {
  // 输入装饰器
  @Input()
  parentProp!: string;

  constructor() { }

  ngOnInit(): void {
  }
}
登入後複製

子元件接受父元件傳入的變數 parentProp,回填到頁面。

<!-- child.component.html -->

<h1>Hello! {{ parentProp }}</h1>
登入後複製

2. 子元件透過Emitter 事件傳遞訊息給父元件

透過new EventEmitter() 將子元件的資料傳遞給父組件。

// child.component.ts

import { Component, OnInit, Output, EventEmitter } from &#39;@angular/core&#39;;

@Component({
  selector: &#39;app-child&#39;,
  templateUrl: &#39;./child.component.html&#39;,
  styleUrls: [&#39;./child.component.scss&#39;]
})
export class ChildComponent implements OnInit {
  // 输出装饰器
  @Output()
  private childSayHi = new EventEmitter()

  constructor() { }

  ngOnInit(): void {
    this.childSayHi.emit(&#39;My parents&#39;);
  }
}
登入後複製

透過 emit 通知父元件,父元件對事件進行監聽。

// parent.component.ts

import { Component, OnInit } from &#39;@angular/core&#39;;

@Component({
  selector: &#39;app-communicate&#39;,
  templateUrl: &#39;./communicate.component.html&#39;,
  styleUrls: [&#39;./communicate.component.scss&#39;]
})
export class CommunicateComponent implements OnInit {

  public msg:string = &#39;&#39;

  constructor() { }

  ngOnInit(): void {
  }

  fromChild(data: string) {
    // 这里使用异步
    setTimeout(() => {
      this.msg = data
    }, 50)
  }
}
登入後複製

在父元件中,我們對 child 元件來的資料進行監聽後,這裡採用了 setTimeout 的非同步操作。是因為我們在子元件中初始化後就進行了 emit,這裡的非同步操作是防止 Race Condition 競爭出錯。

我們也得在元件中加入fromChild 這個方法,如下:

<!-- parent.component.html -->

<h1>Hello! {{ msg }}</h1>
<app-child (childSayHi)="fromChild($event)"></app-child>
登入後複製

3. 透過引用,父元件取得子元件的屬性與方法

我們透過操縱引用的方式,取得子元件對象,然後對其屬性和方法進行存取。

我們先設定子元件的示範內容:

// child.component.ts

import { Component, OnInit } from &#39;@angular/core&#39;;

@Component({
  selector: &#39;app-child&#39;,
  templateUrl: &#39;./child.component.html&#39;,
  styleUrls: [&#39;./child.component.scss&#39;]
})
export class ChildComponent implements OnInit {

  // 子组件的属性
  public childMsg:string = &#39;Prop: message from child&#39;

  constructor() { }

  ngOnInit(): void {
    
  }

  // 子组件方法
  public childSayHi(): void {
    console.log(&#39;Method: I am your child.&#39;)
  }
}
登入後複製

我們在父元件上設定子元件的引用識別#childComponent

<!-- parent.component.html -->

<app-child #childComponent></app-child>
登入後複製

之後在javascript 檔案上呼叫:

import { Component, OnInit, ViewChild } from &#39;@angular/core&#39;;
import { ChildComponent } from &#39;./components/child/child.component&#39;;

@Component({
  selector: &#39;app-communicate&#39;,
  templateUrl: &#39;./communicate.component.html&#39;,
  styleUrls: [&#39;./communicate.component.scss&#39;]
})
export class CommunicateComponent implements OnInit {
  @ViewChild(&#39;childComponent&#39;)
  childComponent!: ChildComponent;

  constructor() { }

  ngOnInit(): void {
    this.getChildPropAndMethod()
  }

  getChildPropAndMethod(): void {
    setTimeout(() => {
      console.log(this.childComponent.childMsg); // Prop: message from child
      this.childComponent.childSayHi(); // Method: I am your child.
    }, 50)
  }

}
登入後複製

這種方法有個限制?,就是子屬性的修飾符需要是public,當是protectedprivate 的時候,會報錯。你可以將子組件的修飾符更改下嘗試。報錯的原因如下:

##public允許在累的內外被調用,作用範圍最廣protected允許在類別內以及繼承的子類別中使用,作用範圍適中private允許在類別內部使用,作用範圍最窄
類型使用範圍

4.透過service 去變動

我們結合

rxjs 來示範。

rxjs 是使用 Observables 的響應式程式設計的函式庫,它使編寫非同步或基於回呼的程式碼更容易。

後會有一篇文章記錄

rxjs,請期待

我們先來建立一個名為

parent-and-child 的服務。

// parent-and-child.service.ts

import { Injectable } from &#39;@angular/core&#39;;
import { BehaviorSubject, Observable } from &#39;rxjs&#39;; // BehaviorSubject 有实时的作用,获取最新值

@Injectable({
  providedIn: &#39;root&#39;
})
export class ParentAndChildService {

  private subject$: BehaviorSubject<any> = new BehaviorSubject(null)

  constructor() { }
  
  // 将其变成可观察
  getMessage(): Observable<any> {
    return this.subject$.asObservable()
  }

  setMessage(msg: string) {
    this.subject$.next(msg);
  }
}
登入後複製

接著,我們在父子元件中引用,它們的資訊是共享的。

// parent.component.ts

import { Component, OnDestroy, OnInit } from &#39;@angular/core&#39;;
// 引入服务
import { ParentAndChildService } from &#39;src/app/services/parent-and-child.service&#39;;
import { Subject } from &#39;rxjs&#39;
import { takeUntil } from &#39;rxjs/operators&#39;

@Component({
  selector: &#39;app-communicate&#39;,
  templateUrl: &#39;./communicate.component.html&#39;,
  styleUrls: [&#39;./communicate.component.scss&#39;]
})
export class CommunicateComponent implements OnInit, OnDestroy {
  unsubscribe$: Subject<boolean> = new Subject();

  constructor(
    private readonly parentAndChildService: ParentAndChildService
  ) { }

  ngOnInit(): void {
    this.parentAndChildService.getMessage()
      .pipe(
        takeUntil(this.unsubscribe$)
      )
      .subscribe({
        next: (msg: any) => {
          console.log(&#39;Parent: &#39; + msg); 
          // 刚进来打印 Parent: null
          // 一秒后打印 Parent: Jimmy
        }
      });
    setTimeout(() => {
      this.parentAndChildService.setMessage(&#39;Jimmy&#39;);
    }, 1000)
  }

  ngOnDestroy() {
    // 取消订阅
    this.unsubscribe$.next(true);
    this.unsubscribe$.complete();
  }
}
登入後複製
import { Component, OnInit } from &#39;@angular/core&#39;;
import { ParentAndChildService } from &#39;src/app/services/parent-and-child.service&#39;;

@Component({
  selector: &#39;app-child&#39;,
  templateUrl: &#39;./child.component.html&#39;,
  styleUrls: [&#39;./child.component.scss&#39;]
})
export class ChildComponent implements OnInit {
  constructor(
    private parentAndChildService: ParentAndChildService
  ) { }
  
  
  // 为了更好理解,这里我移除了父组件的 Subject
  ngOnInit(): void {
    this.parentAndChildService.getMessage()
      .subscribe({
        next: (msg: any) => {
          console.log(&#39;Child: &#39;+msg);
          // 刚进来打印 Child: null
          // 一秒后打印 Child: Jimmy
        }
      })
  }
}
登入後複製
在父元件中,我們一秒鐘之後會改變值。所以在父子元件中,一進來就會印出

msg 的初始值null,然後過了一秒鐘之後,就會印出更改的值Jimmy# 。同理,如果你在子元件中對服務的訊息,在子元件列印相關的值的同時,在父元件也會列印。更多程式設計相關知識,請造訪:程式設計入門! !

以上是帶你了解Angular組件間進行通訊的幾種方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

如何在Ubuntu 24.04上安裝Angular 如何在Ubuntu 24.04上安裝Angular Mar 23, 2024 pm 12:20 PM

Angular.js是一種可自由存取的JavaScript平台,用於建立動態應用程式。它允許您透過擴展HTML的語法作為模板語言,以快速、清晰地表示應用程式的各個方面。 Angular.js提供了一系列工具,可協助您編寫、更新和測試程式碼。此外,它還提供了許多功能,如路由和表單管理。本指南將討論在Ubuntu24上安裝Angular的方法。首先,您需要安裝Node.js。 Node.js是一個基於ChromeV8引擎的JavaScript運行環境,可讓您在伺服器端執行JavaScript程式碼。要在Ub

一文探究Angular中的服務端渲染(SSR) 一文探究Angular中的服務端渲染(SSR) Dec 27, 2022 pm 07:24 PM

你知道 Angular Universal 嗎?可以幫助網站提供更好的 SEO 支援哦!

angular學習之詳解狀態管理器NgRx angular學習之詳解狀態管理器NgRx May 25, 2022 am 11:01 AM

這篇文章帶大家深入了解angular的狀態管理器NgRx,介紹一下NgRx的使用方法,希望對大家有幫助!

如何使用PHP和Angular進行前端開發 如何使用PHP和Angular進行前端開發 May 11, 2023 pm 04:04 PM

隨著網路的快速發展,前端開發技術也不斷改進與迭代。 PHP和Angular是兩種廣泛應用於前端開發的技術。 PHP是一種伺服器端腳本語言,可以處理表單、產生動態頁面和管理存取權限等任務。而Angular是一種JavaScript的框架,可以用來開發單一頁面應用程式和建構元件化的網頁應用程式。本篇文章將介紹如何使用PHP和Angular進行前端開發,以及如何將它們

淺析angular中怎麼使用monaco-editor 淺析angular中怎麼使用monaco-editor Oct 17, 2022 pm 08:04 PM

angular中怎麼使用monaco-editor?以下這篇文章記錄下最近的一次業務中用到的 m​​onaco-editor 在 angular 中的使用,希望對大家有幫助!

淺析Angular中的獨立組件,看看怎麼使用 淺析Angular中的獨立組件,看看怎麼使用 Jun 23, 2022 pm 03:49 PM

這篇文章帶大家了解Angular中的獨立元件,看看怎麼在Angular中建立一個獨立元件,怎麼在獨立元件中導入已有的模組,希望對大家有幫助!

使用Angular和Node進行基於令牌的身份驗證 使用Angular和Node進行基於令牌的身份驗證 Sep 01, 2023 pm 02:01 PM

身份驗證是任何網路應用程式中最重要的部分之一。本教程討論基於令牌的身份驗證系統以及它們與傳統登入系統的差異。在本教程結束時,您將看到一個用Angular和Node.js編寫的完整工作演示。傳統身份驗證系統在繼續基於令牌的身份驗證系統之前,讓我們先來看看傳統的身份驗證系統。使用者在登入表單中提供使用者名稱和密碼,然後點擊登入。發出請求後,透過查詢資料庫在後端驗證使用者。如果請求有效,則使用從資料庫中獲取的使用者資訊建立會話,然後在回應頭中傳回會話訊息,以便將會話ID儲存在瀏覽器中。提供用於存取應用程式中受

專案過大怎麼辦?如何合理拆分Angular項目? 專案過大怎麼辦?如何合理拆分Angular項目? Jul 26, 2022 pm 07:18 PM

Angular專案過大,怎麼合理拆分它?以下這篇文章跟大家介紹一下合理分割Angular專案的方法,希望對大家有幫助!

See all articles