如何在 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` 装饰器装饰属性。在父组件中,我们使用属性绑定将其绑定到父组件的属性或方法。

更新于:2023年2月21日

12K+ 次查看

启动你的 职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.