【发布时间】: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