Angular-将单选按钮值放入对象数组

时间:2018-12-03 09:07:22

标签: angular typescript radio-button

我正在研究简单的问题申请。用户将获得n + 1个问题。每个问题都有多个选择,可以通过单选按钮实现。此外,每个问题都有可能添加评论。

我现在正在前端站点上工作。我嘲笑了一些问题,我想将JSON对象放在一起发送给后端。

我的问题是我无法从单选按钮值中获得所谓的答案。

我的代码:

interviewanswer.ts

export class Interviewanswer
{
  answer: string;
  comment: string;
}

formfill.component.ts

import { Component, OnInit } from '@angular/core';
import {QUESTIONS} from '../mockedData/mock-questions';
import {Interviewanswer} from '../model/interviewanswer';



@Component({
selector: 'app-formfill',
templateUrl: './formfill.component.html',
styleUrls: ['./formfill.component.css']
})
export class FormfillComponent implements OnInit {

  constructor() { }

  questions = QUESTIONS;

  answertypes = ['2 times in a week', '2 times in a month', '2 times in a year', 'Cannot comment'];

  answers: Interviewanswer[];

  name: string;
  position: string;


  ngOnInit() {
  }

  saveData()
  {



    const person =
    {
        name: this.name,
        position: this.position,
        answers: this.answers


    };
 console.log(person);

formfill.component.html

<mat-tab-group>
  <mat-tab label="Personal data">
    <mat-form-field>
      <input matInput placeholder="Name" [(ngModel)]="name">
    </mat-form-field>
    <br>

    <mat-form-field>
      <textarea matInput placeholder="Position" [(ngModel)]="position"></textarea>
    </mat-form-field>
  </mat-tab>
  <mat-tab label="Questions">



    <mat-grid-list cols="3" rowHeight="3:2" *ngFor="let q of questions; let i = index; let a of answers">

      <mat-grid-tile>{{i+1}}.  {{q.question}}</mat-grid-tile>
      <mat-grid-tile>

        <mat-radio-group class="mat-radio-group" [(ngModel)]="a.answer">
          <mat-list>
            <mat-list-item><mat-radio-button [value]=answertypes[0]>2 times in a week</mat-radio-button></mat-list-item>
            <mat-list-item><mat-radio-button [value]=answertypes[1]>2 times in a month</mat-radio-button></mat-list-item>
            <mat-list-item><mat-radio-button [value]=answertypes[2]>2 times in a year</mat-radio-button></mat-list-item>
            <mat-list-item><mat-radio-button [value]=answertypes[3]>Cannot comment</mat-radio-button></mat-list-item>
          </mat-list>
        </mat-radio-group>


      </mat-grid-tile>
      <mat-grid-tile>

        <mat-form-field>
          <textarea matInput placeholder="Comment" [(ngModel)]="a.comment"></textarea>
        </mat-form-field>

      </mat-grid-tile>
    </mat-grid-list>

    <br>
    <button mat-button (click)="saveData()">Save</button>

  </mat-tab>
</mat-tab-group>

当我将对象人打印到控制台中时,我可以得到名称和位置,但是对答案却未定义。 我需要的输出是这样的:     {name:“ Jan”,position:“ developer”,     答案:[{answer:“一周两次”,评论:“也许更多”},{answer:“无法说”,评论:“我没有评论”} ...]

我想念什么?任何帮助都很好!

谢谢!

0 个答案:

没有答案