Reputation: 161
I have three questions in my Angular reactive form which is very basic .
I want to display only one question at a time to the user and on clicking the next button , the next question should appear . (There should be a next button underneath every question). Please help me achieve this . Thanks in advance .
Upvotes: 1
Views: 2303
Reputation: 7156
I have done this in your Reactive Form itself. Please check.
Component
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')
])
});
}
HTML
<form [formGroup]="myForm" (ngSubmit)="onSubmit(myForm)">
What is your name ? <input formControlName="name" placeholder="Your name"><br>
What is your email? <input formControlName="email" placeholder="Your email"><br>
What is your message? <input formControlName="message" placeholder="Your message"><br>
<p>
Questions: {{ myForm.get('questions').value[currentQuestionIndex] }}
</p>
<button type="button" (click)="currentQuestionIndex = currentQuestionIndex - 1">Previous</button>
<button type="button" (click)="currentQuestionIndex = currentQuestionIndex + 1">Next</button>
</form>
Upvotes: 0
Reputation: 22203
You can make the process dynamic by keeping the questions in an array.
Try like this:
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}
]
Template:
<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>
Upvotes: 1
Reputation: 304
In your app.component.ts declare
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>
After clicking next button step variable increments by one and it will show you the next question. Stack Blitz Link
Upvotes: 0