【问题标题】:Angular: How to interact components from Parent component to child componentAngular:如何将组件从父组件交互到子组件
【发布时间】:2021-09-21 07:08:48
【问题描述】:

有两个组件,一个是顶部面板(父)和显示(子)组件。我尝试输入一些值,例如名字、姓氏、电子邮件,然后单击按钮以在子组件空间中显示输入的值(例如:Andy John test@test.com)。您能否帮我在单击按钮时如何在父组件与子组件之间进行交互。

这里是Example

【问题讨论】:

标签: angular


【解决方案1】:

您可以像这样向子组件添加属性:

import { Component } from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
  @Input() firstname: string;
}

像这样从父级的 html 模板向下传达它们:

<app-child [firstname]="firstname"></app-child>

并将它们显示在孩子的 html 模板中,如下所示:

Hello {{firstname}}

【讨论】:

    【解决方案2】:

    在你的代码中有一些错误

    1. 您没有放置任何选择器,即:
    2. 没有写如何在 child 中显示值。

    更多详情请参考:

    ->https://angular.io/guide/inputs-outputs

    ->https://angular.io/guide/component-interaction

    出于您的目的,请检查您编辑的示例:https://stackblitz.com/edit/angular7-communication-between-components-coqvnq?file=src%2Fapp%2Fchild%2Fchild.component.html 使用@Input 指令

    说明

    这里在父组件中更改为带有formcontrols -firstname、lastname、email 等的表单。单击按钮时,使用.push 将表单值添加到array-parentVar。 在 parent.componet.html 中,我们添加了 childcomponet 指令为

    <app-child [parentOutputVar]="parentVar"></app-child>
    

    parent.component 中的 parentVar 将数据作为输入发送到 app-child ([parentOutputVar]="parentVar")。

    数据将使用结构指令显示 -ngIf &ngFor

    【讨论】:

      【解决方案3】:

      为了在父子组件之间共享数据,我们使用 @Input()@Output() 装饰器。

      第一步是在父子组件之间建立层次结构。 &lt;parent-component&gt;&lt;child-component&gt; 提供上下文

      在讨论的两个装饰器@Input@Output 中,@Input 装饰器允许父组件更新子组件中的数据,@Output 装饰器允许子组件向父组件发送数据。

      您的要求指定,在单击submit 按钮时从父组件向子组件发送数据。您首先需要为此配置子组件,

      • 在您的 child.component.ts 中, 添加@Input()并用它装饰属性,如下所示,
      @Input() formData: any = [];
      
      • 在您的 parent.component.ts 中, 使用子选择器&lt;app-child [formData] = "formValue"&gt;&lt;/app-child&gt; 作为其模板中的指令。这里我们使用属性绑定将父级的formValue 属性绑定到子级的formData 属性。

      TLDR;

      请查找说明父子数据通信的 StackBlitz 项目。

      在这里,我更新了您提供的示例,以使用 Input() 装饰器显示在您的子组件内的表单中输入的值。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-04-16
        • 2021-02-15
        • 2020-04-05
        • 2017-06-25
        • 1970-01-01
        • 2020-09-21
        • 1970-01-01
        • 2021-04-07
        相关资源
        最近更新 更多