I made a reactive form, where user can add data. There I have added a add
button and a remove
button. While clicking the add
button user can add more input fields and remove those fields while clicking remove
. Now I want to keep remove
button hidden if there is only one input field. How do i do it?
The HTML code:
<div >
<div >
<div style="display: flex;">
<span>Add custom questions:</span>
<mat-checkbox
style="margin-left: 10px! important;"
(change)="selectCheck()"
>
</mat-checkbox>
</div>
<div *ngIf="checked">
<span style="font-style: italic; font-size: 9px;"
>NOTE : Panel members can respond with text based answers, which will be
visible to the winner selector</span
>
<form [formGroup]="userForm">
<div
*ngFor="let question of getQuestionFormControls(); let i = index"
>
<span >Question {{ i 1 }}</span>
<input
[formControl]="questions"
type="text"
/>
</div>
<div
style="display:flex;align-items:center;"
>
<!-- <i ></i> -->
<div >
<mat-icon
style="color: #5663ED;cursor:pointer;margin-top: 0rem;"
(click)="addQuestion()"
>add_box</mat-icon
>
<span>Add more questions</span>
</div>
<div >
<mat-icon
(click)="removeQuestion(i)"
style="color: #5663ED;cursor:pointer"
>remove_circle</mat-icon
>
<span>Remove</span>
</div>
</div>
</form>
</div>
</div>
</div>
The ts code:
checked = false;
userForm: FormGroup;
constructor(private fb: FormBuilder) {
this.userForm = new FormGroup({
questions: this.fb.array([this.fb.control(null)]),
});
}
addQuestion(): void {
(this.userForm.get('questions') as FormArray).push(this.fb.control(null));
}
removeQuestion(index) {
(this.userForm.get('questions') as FormArray).removeAt(index);
}
getQuestionFormControls(): AbstractControl[] {
return (<FormArray>this.userForm.get('questions')).controls;
}
selectCheck() {
this.checked = !this.checked;
}
I tried to use *ngif="i >= 1"
with the hopes of using the index, but it didn't work. What do I do?
A demo of the project
CodePudding user response:
I didn't tested it, but i guess this could work fine:
<div
*ngIf="(this.userForm.get('questions'))?.length > 1"
>
<mat-icon
(click)="removeQuestion(i)"
style="color: #5663ED;cursor:pointer"
>remove_circle</mat-icon
>
<span>Remove</span>
</div>
If it doesn't work, try to change this line:
*ngIf="(this.userForm.get('questions'))?.controls?.length > 1"