如何在 Angular 8 中將資料從父元件傳遞到子元件?
在 Angular 8 中,要將資料從父元件傳遞到子元件,我們使用 `@Input` 裝飾器。`@Input` 裝飾器是 Angular 中的屬性裝飾器之一。現在,讓我們瞭解一下 `@Input` 裝飾器如何在父元件和子元件之間工作。
前提條件
在繼續之前,我們需要一些前提條件,例如:
Angular 的基礎知識。
已安裝 WebStorm、Intellij 或 Visual Studio/Code 等 IDE。
必須安裝 Angular CLI。
必須安裝 Node.js。
步驟
這裡,我解釋了將資料從父元件傳遞到子元件的步驟。
首先建立 Angular 專案。
使用 NPM 命令建立父元件和子元件。
在子元件中匯入 `@Input` 裝飾器。
在子元件中匯入 `@Input` 裝飾器。
在 HTML 中定義 `@Input`。
現在,在父元件中,需要建立一個帶有子元件選擇器的標籤,並使用屬性繫結來繫結 `@Input` 值的名稱。
在父元件中,為定義的值賦值。
讓我們詳細說明這些步驟。
現在,讓我們使用 NPM 命令建立 Angular 專案。例如:
npm new sampleProject
npm new sampleProject
npm g c parent
使用 NPM 命令建立子元件。例如:
npm g c child
這裡,`g` 表示生成,`c` 表示元件。我們也可以使用以下命令:
npm generate component componentName
我們可以在 VS 或任何 IDE 中手動建立元件。或者,我們可以使用命令。當我們使用命令生成元件時,它將建立四個與元件名稱相關的檔案。一個是 `.ts` 檔案,第二個是 `.html` 檔案,第三個是 `.spec.ts` 檔案,最後一個是 `.css` 檔案。最簡單的方法是使用命令列。現在讓我們來看程式碼部分。
示例
在 **child.component.ts** 檔案中,編寫如下程式碼:
import { Component, Input } from "@angular/core"; @Component({ selector: "app-child", templateUrl: "./child.component.html", styleUrls: ["./child.component.css"] }) export class ChildComponent { @Input() message = ""; Constructor() {} }
在這裡,我們使用 `@Input` 裝飾器定義了 `message`。現在,讓我們在 HTML 檔案中新增程式碼。
在 **child.component.html** 檔案中:
<div id="child"> <p>Child Component</p> <p id="messageFromParent">{{ message }}</p> </div>
現在,定義要從父元件傳送到子元件的資料。例如:
在 **parent.component.ts** 檔案中:
import { Component } from "@angular/core"; @Component({ selector: "app-parent", templateUrl: "./parent.component.html", styleUrls: ["./parent.component.css"] }) export class ParentComponent { constructor() {} parentMessage = "Message from the parent to the child"; }
在 **parent.component.html** 檔案中:
<div id="child"> <p>Child Component</p> <p id="messageFromParent">{{ message }}</p> </div>
請記住,這裡的 `message`(即屬性繫結)與我們在子元件中使用 `@Input` 定義的名稱相同。我們在 `@Input` 中提到的任何名稱,都需要在父元件中使用繫結來提及相同的名稱。
我們為 `parentMessage` 分配的任何文字都將被子元件訪問。這將透過 `{{ message }}` 表示式顯示。
我們建立了子元件和父元件。我們定義了資料並編寫了顯示程式碼。
現在,讓我們在主模組(即 **app.module.ts** 檔案)中匯入這兩個元件。
import { BrowserModule } from "@angular/platform-browser"; import { NgModule } from "@angular/core"; import { AppComponent } from "./app.component"; import { ChildComponent } from "./child.component"; import { ParentComponent } from "./parent.component"; @NgModule({ declarations: [AppComponent, ChildComponent, ParentComponent], imports: [BrowserModule], providers: [], bootstrap: [AppComponent] }) export class AppModule {}
在這裡,我們將服務類作為提供程式匯入。在 `@NgModule` 中,我們有四個部分。
宣告 - 定義匯入的元件
匯入 - 定義匯入的模組
提供程式 - 定義匯入的服務
引導 - 定義要顯示資料的根元件
現在讓我們在 app-component.html 中新增父選擇器以顯示結果
在 **app.component.html** 檔案中
<div> <p>Main page</p> <app-parent></app-parent> </div>
輸出
Main page Parent Component Child Component Message from the parent to the child
從上面,我們學習瞭如何使用 `@Input` 裝飾器將資料從父元件傳遞到子元件。子元件使用 `@Input` 裝飾器裝飾屬性。在父元件中,我們使用屬性繫結將其繫結到父元件的屬性或方法。