簡體   English   中英

如何在 Angular 中將變量從組件檢索到另一個? (不在 Html 頁面中,而是在組件中)

[英]How to retrieve variable from component to another in Angular? (not in the Html page, but in the component)

在子組件中,我有一個字符串:

@Input() helloMessage:string;

我需要這個字符串從父組件的另一個字符串中獲取值,並將這個值訪問到子組件中。 我不需要在 html 中顯示該值,而且我不知道如何從父組件傳遞訪問該變量。 所以this.helloMessage=parentComponentVariable ,因為我需要在子組件的方法中使用 helloMessage 變量。

這是一個基本的數據綁定概念。 嘗試類似於以下內容。 子組件 TS 文件

@Input() helloMessageChild:string;

父組件 TS 文件

helloMessageParent = '';

提供組件 HTML 文件

<app-child-component [helloMessageChild]="helloMessageParent"></app-child-component>

https://angular.io/guide/two-way-binding

這是標准方式。 如果出於任何原因不想進行數據綁定,則必須將服務與 BehaviorSubject 一起使用。 您必須從父級發出數據並訂閱子級發出的數據。

https://medium.com/@weswhite/angular-behaviorsubject-service-60485ef064fc

在實踐中,服務用於將數據從一個組件傳遞到另一個沒有父子關系的組件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM