Search code examples
angulartypescriptangular-materialangular-components

How to dynamically add a pair of text input and textarea in Angular 8?


The following piece of html is from our angular page where a user is supposed to introduce a question and its respective answer (something like Q&A thing).

 <mat-card>
           <button mat-stroked-button color="primary" style="margin-right: 20px;">
               Add a new Q & A pair
            </button>
            </mat-card>
            <div *ngFor="let qna of interview.qnas">
                <mat-card id="{{qna.id}}" style="margin-bottom: 25px;">
                    <mat-form-field>
                        <input matInput type="text" class="form-control" placeholder="Interview question" required [(ngModel)]="qna.question" name="question">
                    </mat-form-field> 
                    <mat-form-field>
                        <textarea matInput rows="5" class="form-control" placeholder="Ideal answer from the talent" [(ngModel)]="qna.answer" name="answer"></textarea>
                    </mat-form-field>
                    <button mat-stroked-button color="warn">
                        Remove this
                    </button>
                </mat-card> 
            </div>

As you can see in the HTML, there are two buttons in there, the first button is supposed to let users add a new pair of and and the 2nd one is supposed to remove a pair. I can probably come up with a solution for removing the pair but I am not so sure how to implement adding a new Q&A pair on the fly when the user clicks on it. Also, please consider that we have two-way binding in place too.


Solution

  • <mat-card>
        <button mat-stroked-button color="primary" style="margin-right: 20px;"
                (click)="addQnApair()">
            Add a new Q & A pair
        </button>
    </mat-card>
    <div *ngFor="let qna of interview.qnas; let i= index">
        <mat-card id="{{qna.id}}" style="margin-bottom: 25px;">
            <mat-form-field>
                <input matInput type="text" class="form-control"
                       placeholder="Interview question" required [(ngModel)]="qna.question"
                       name="question">
            </mat-form-field>
            <mat-form-field>
                            <textarea matInput rows="5" class="form-control"
                                      placeholder="Ideal answer from the talent" [(ngModel)]="qna.answer"
                                      name="answer"></textarea>
            </mat-form-field>
            <button mat-stroked-button color="warn"
                    (click)="removeQnApair(i)">
                Remove this
            </button>
        </mat-card> 
    </div>
    

    In ts file

    removeQnApair(i) {
        this.interview.qnas.splice(i,1);
         }
    
    addQnApair(){
       this.interview.qnas.push({id: this.interview.qnas.length+1,
                    question: '',
                    answer: ''});
       }