What is the best way to programmatically include a text input and textarea together in an Angular 8 application?

This HTML snippet is taken from our Angular page, where users can enter a question and its corresponding answer (similar to a Q&A feature).

 <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>

In the provided HTML code, there are two buttons - one for adding a new Q&A pair and the other for removing a pair. While I can figure out how to remove a pair, the challenge lies in dynamically adding a new Q&A pair when the user clicks on the button. It's important to note that we have two-way binding implemented as well.

Answer №1

<mat-card>
    <button mat-stroked-button color="primary" style="margin-right: 20px;"
            (click)="addQuestionAnswerPair()">
        Add a new Question & Answer pair
    </button>
</mat-card>
<div *ngFor="let qna of interview.questionsAndAnswers; 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)="removeQuestionAnswerPair(i)">
            Remove this
        </button>
    </mat-card> 
</div>

In ts file

removeQuestionAnswerPair(i) {
    this.interview.questionsAndAnswers.splice(i,1);
     }

addQuestionAnswerPair(){
   this.interview.questionsAndAnswers.push({id: this.interview.qnas.length+1,
                question: '',
                answer: ''});
   }

Answer №2

Check out this code snippet:

 <mat-card>
           <button mat-stroked-button color="primary" style="margin-right: 20px;">
               Click here to 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 value="{{qna.question}}" name="question">
                    </mat-form-field> 
                    <mat-form-field>
                        <textarea matInput rows="5" class="form-control" placeholder="Ideal answer from the talent"  value="{{qna.answer}}" name="answer"></textarea>
                    </mat-form-field>
                    <button mat-stroked-button color="warn">
                        Delete this entry
                    </button>
                </mat-card> 
            </div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing the disappearance of my Angular 6 Service object variable upon refreshing the component it's injected into?

Recently, I encountered an issue with a SERVICE named test.service, which contains an object: public locationObject = { ...... ...... currency: string } In my project, this SERVICE is injected into the HeaderComponent and the object locationObj ...

Diving into Angular 2 RC6: Understanding the Differences Between Modules and Components

I'm feeling a bit overwhelmed with RC6 of angular2. I'm struggling to figure out how to adjust my code with modules and components and I'm confused about the distinctions between the two. Can you assist me in incorporating directives, provid ...

Tips for integrating custom code into your Angular cli service worker

Although I have successfully generated and configured the service worker using a config file generated by Angular CLI, I am struggling to find documentation on how to add custom code to the ngsw-worker.js file. I want to include functions such as push no ...

Manage numerous receiving bank accounts, allowing customers to transfer money to each specific account

Managing multiple receiving bank accounts and enabling customers to transfer money to specific accounts is a key requirement in my application. Can Plaid help me achieve this functionality? Could you provide guidance on how to implement this feature using ...

Sorry, I can't do that task as it involves paraphrasing content that is already provided to me. How about I summarize the text instead?

I encountered an error while attempting to fetch data from an API for my Ionic 5 application. I attempted removing all the arrays but unfortunately, it did not resolve the issue. Can someone please provide assistance? Below are the files being used: type ...

Is there a way for me to consolidate the properties of a complex nested object into the top level of an array of objects through either moving or summing them up?

I have a collection array that looks like this: const collection = [ { "name": "Top1", "data": [ { "name": "shahnshah", "data": [ { ...

Which approach is more effective: utilizing a single event binding with several functions or multiple event bindings with just one function?

Which format is better: <a (click)="f1(); f2()"> or <a (click)="f1()" (click)="f2()">? The order does not matter to me, and I prefer not to create an additional function to call both. ...

The useState variable remains unchanged even after being updated in useEffect due to the event

Currently, I am facing an issue in updating a stateful variable cameraPosition using TypeScript, React, and Babylon.js. Below is the code snippet: const camera = scene?.cameras[0]; const prevPositionRef = useRef<Nullable<Vector3>>(null); ...

Unable to utilize Stats.js with @angular/cli version 1.4.4

Attempting to utilize @types/stats with @angular/cli following the guidance at https://github.com/angular/angular-cli/wiki/stories-third-party-lib. However, encountering a tslint error when trying to import * as STATS from 'stats.js'. [ts] Modul ...

Tips for sending FormData and request body with angular's httpclient

I need help updating my Angular application package from @angular/http to @angular/common/http. During the process, my code is breaking for a specific reason. Previously, I was able to send both form data and request body in the following manner: this.ht ...

Unlocking the Power of Custom Fontawesome Icons in Ionic3 ActionSheet

I've been struggling with incorporating custom Fontawesome icons into my ActionSheet buttons in Ionic3. Previously, I was able to use code like this: <i class="fas fa-ad"></i> within the title/text property of the actionsheet button to d ...

How can I extract an array from a nested array using TypeScript?

How do I retrieve a nested array? const result = resultList.map((location) => location.options.map(option => {return option.someOptions})); console.log(result); I am looking to extract an array from a nested array, if (result.flat().includes(&apos ...

Every time I try to install a particular version of angular using angular cli, it seems to result in the incorrect version

_ _ ____ _ ___ / \ _ __ __ _ _ _| | __ _ _ __ / ___| | |_ _| / △ \ | '_ \ / _` | | | | |/ _` | '__| | | | | | | / ___ \| | | | (_| | |_| | | (_| | | | ...

Is it possible to automatically correct all import statements in a TypeScript project?

After transferring some class member variables to a separate class in another file, I realized that these variables were extensively used in the project. As a result, approximately 1000 .ts files will need their imports modified to point to the new class/f ...

TypeScript making erroneous assumptions about property values post-setting

My TypeScript object has a boolean property that causes some confusion. When I update the object's value to false, TypeScript seems to believe it will remain false indefinitely (at least within the scope), even though it can be modified: const obj = { ...

Compilation error occurred during the module build process at ./node_modules/sass-loader/dist/cjs.js

Encountered an error while attempting to run my Angular 9 app on Windows 10 locally. The specific error message is as follows: ERROR in ./src/assets/sass/pickandpay.scss (./node_modules/css-loader/dist/cjs.js??ref--13-1!./node_modules/postcss-loader/src? ...

Make the switch from TypeScript namespaces to ES2015 modules

After making adjustments to my TypeScript configuration, I am now encountering errors related to the no-namespace rule. Here is how my current setup involving namespaces looks like: Exporting classes within a namespace: namespace MyNamespace { export ...

Designing the Firebase Structure of an Angular Application

What is the best way to structure Firestore and Angular for efficient querying? When using a JSON Cloud Firestore database, one of the challenges is inserting people and relating them to users. To optimize query speed and efficiency, it is important to c ...

After reinstallation, Angular CLI is still not functioning properly

I recently tried to upgrade my Angular CLI by uninstalling it and installing the new version. However, I encountered an issue where I am unable to run ng commands anymore due to an error message that keeps appearing: ng : File C:\Users\Sirius&bso ...

Typescript displays an error message when attempting to assign a list of string variants to a defined type

Encountering an interesting TS error in the code snippet below: interface Bar { pictureType: "X" | "Y" } interface RT { output: Bar[] } const func = (): RT => { const list = [{ pictureType: 'X', }] r ...