【问题标题】:How do I collect entered data from child components created by ngFor in parent component?如何从父组件中由 ngFor 创建的子组件收集输入的数据?
【发布时间】:2019-11-29 08:47:03
【问题描述】:

我有一个组件会提出 1 个问题并将 1 个答案返回给父组件。

问题是: 我不知道如何访问从子组件传递的数据。

这是我的代码:

child.component.html:

<mat-card>
  <mat-card-header>
    <mat-card-subtitle>Question {{this.row}}</mat-card-subtitle>
  </mat-card-header>
  <mat-card-content>
    <mat-form-field>
      <input  matInput
              required
              [placeholder]="placeholder"
              autocomplete="off"
              [(ngModel)]="value">
    </mat-form-field>
    </mat-card-content>
 </mat-card>

child.component.ts:

import { Component, OnInit, Input, Output, EventEmitter, AfterViewInit } from '@angular/core';
@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.scss']
})
export class ChildComponent implements OnInit {
  value: string;
  @Input() row: number;
  @Input() placeholder: string;

  constructor() { }

  ngOnInit() { }
}

parent.component.html:

<p>
  Questions!
</p>
<app-child  *ngFor="let question of questions"
            [placeholder]="question.question"
            [row]="question.row">
</app-child>

parent.component.ts:

import { ChildComponent } from './../child/child.component';
import { Component, OnInit, ViewChild, AfterViewInit, Output } from '@angular/core';

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.scss']
})

export class ParentComponent implements OnInit, AfterViewInit {
  parentvalue: string;
  value: string;
  parentData: string;
  @ViewChild(ChildComponent, {static: false}) childReference: ChildComponent;


  questions: any[] = [
    {row: 1, question: 'What`s your name?' },
    {row: 2, question: 'How old are you?' },
    {row: 3, question: 'where did you born?' },
    {row: 4, question: 'What`s your father`s name?' },
    {row: 5, question: 'Who is your childhood hero?' },
  ];

  constructor() { }

  ngOnInit() {}

  viewchildmethod() {
    this.parentvalue = this.childReference.value;
  }
}

如何分别收集答案?

【问题讨论】:

    标签: angular


    【解决方案1】:

    有几种方法。

    1.对象的操作

    但这里最简单的方法之一是将整个对象传递给子对象,而不仅仅是对象的原始属性。您可以使用数组和对象的可变性...

    https://stackblitz.com/edit/angular-mptuxa-6jgz7a

    这样做,你就有了价值的参考。

    2。使用事件发射器:

    将 EventEmitter 添加到您的孩子。

    https://stackblitz.com/edit/angular-mptuxa-nut3ut

    3.使用服务传递更改的值

    。 . . . . . .

    -- 但是,如果您阅读官方示例(https://angular.io/guide/forms-overview),则可以轻松回答这些问题。 --

    【讨论】:

    • 非常感谢。我认为这将正常工作。但我不打算操纵 Questions 对象。实际上我想通过它的数据传递机制访问由 *ngFor 创建的每个组件。你还有其他优惠吗?
    猜你喜欢
    • 2022-11-23
    • 2021-04-12
    • 1970-01-01
    • 1970-01-01
    • 2020-05-27
    • 2020-05-03
    • 2016-01-19
    • 1970-01-01
    • 2019-08-24
    相关资源
    最近更新 更多