一次以Angular反应形式显示一个问题

时间:2019-11-01 06:35:17

标签: angular angular-reactive-forms

我的Angular反应形式有三个基本问题。

我想一次只向用户显示一个问题,然后单击“下一步”按钮,应显示下一个问题。 (每个问题下方应有一个下一个按钮)。请帮助我实现这一目标。预先感谢。

stackblitz Code

3 个答案:

答案 0 :(得分:1)

通过将问题排列在一个数组中,可以使过程动态化。

尝试这样:

Working Demo

TS:

  questions = [
    {type: "name", description : "What is your name ?", isHidden:false},
    {type: "email", description : "What is your email ?", isHidden:true},
    {type: "message", description : "What is your message ?", isHidden:true}
  ]

模板:

<form [formGroup]="myForm" (ngSubmit)="onSubmit(myForm)">
    <ng-container *ngFor="let item of questions;let i = index">
        <div [hidden]="item.isHidden">
            {{item.description}} <input [formControlName]="item.type" placeholder="Your {{item.type}}"><br>
            <button  (click)="questions[i].isHidden = true;questions[i + 1] ?questions[i + 1].isHidden = false : false">Next</button>
        </div>
    </ng-container>
</form>

答案 1 :(得分:0)

在您的app.component.ts中声明

step = 1;

app.component.html

<form [formGroup]="myForm" (ngSubmit)="onSubmit(myForm)">
  <ng-container *ngIf="step >= 1">
    What is your name ? <input formControlName="name" placeholder="Your name"><br>
  </ng-container>
  <ng-container *ngIf="step >= 2"> 
  What is your email? <input formControlName="email" placeholder="Your email"><br>
  </ng-container>
  <ng-container *ngIf="step >= 3">
    What is your message? <input formControlName="message" placeholder="Your message"><br>
  </ng-container>
  <button *ngIf="step <= 2" (click)="step = step + 1;">Next</button>

</form>

单击下一步按钮后,步骤变量将增加1,它将显示下一个问题。 Stack Blitz Link

答案 2 :(得分:0)

我已经在您的反应式表单中完成了此操作。请检查。

Stackblitz Working Exmaple

  

组件

<script>
  new Chart(document.getElementById("leads-bar"), {
    type: 'horizontalBar',
    data: {
      labels: ["Hot", "Warm", "Cold"],
      datasets: [
        {
          backgroundColor: ["#d23232", "#ff9347", "#bbbbbb"],
          data: [7, 9, 11]
        }
      ]
    },
    options: {
      legend: {
        display: false
      },
      tooltips: {
        display: false
      },
      title: {
        display: false
      },
      scales: {
        xAxes: [{
          stacked: true,
          gridLines: {
            display: false,
            drawBorder: false,
          },
          scaleShowLabels: false,
        }],
        yAxes: [{
          stacked: false,
          gridLines: {
            color: ["#eeeeee"]
          }
        }]
      }
    }
  });
  

HTML

  myForm: FormGroup;
  currentQuestionIndex = 0;
  ngOnInit() {
    this.myForm = new FormGroup({
      name: new FormControl('Benedict'),
      email: new FormControl(''),
      message: new FormControl(''),
      questions: new FormArray([
        new FormControl('This is Q1'),
        new FormControl('This is Q2'),
        new FormControl('This is Q3')
      ])
    });
  }