Incorporate form information into an array in Angular Version 2 or higher

This form is where I craft my questions

https://i.sstatic.net/93781.png

When composing a question, the ability to include multiple alternatives is available. There will also be an option to edit these alternatives.

The desired format for my array is as follows:

{
"Question": "Question test",
"cod" : "pw3"
"Value" : "10"
  "Alternatives": [
    {
      "test": "test",
      "test2": "test",
      "test3": "test"
    },
  ]
}

Clicking on the add button allows for an unlimited number of alternatives to be added.

The code responsible for displaying the alternatives is shown below:

<table>
    <thead><tr><th>Name</th><th>Action</th></tr>
    </thead>
    <tbody>
      <tr *ngFor="let quiz of quizes">
        <td>
          <input name="alternativa" type="text" [(ngModel)]="quiz.pergunta" [disabled]="!quiz.isEditable"/>
        </td>
        <td>
          <button (click)="quiz.isEditable=!quiz.isEditable" *ngIf="!quiz.isEditable">Edit</button>
          <button *ngIf="quiz.isEditable" (click)="quiz.isEditable=!quiz.isEditable">Save</button>
        </td>
      </tr>
    </tbody>
  </table>

  <div class="ui-g-2 ui-md-2 ui-lg-2 ui-fluid espacamento-baixo">
    <p-button label="Salvar"></p-button>
  </div> 

I am seeking guidance on how to update the array when I click Save to finalize the question.

Answer №1

It appears that the field labeled "Alternatives" may need to be adjusted in your code. Consider structuring it as follows:

"Alternatives: [{'test':'testAnswer'},{'test2':'test2Answer'}... ]

To iterate over these alternatives using *ngFor, you can follow this pattern:

You could potentially implement the following approach:

let form = {
"Question": "Question test",
"cod" : "pw3",
"Value" : "10",
"Alternatives": [
  {
  "test": "test",
  "test2": "test",
  "test3": "test"
  },
 ]
};

Additionally, consider creating a function to manage adding or removing items from the inner array, like so:

public addOrRemoveItemInArray(a:boolean) {
// if a=true, add if false = remove
if (a === true) { 
let newAnswer = {"test": ""};
this.form.Alternatives.push(newAnswer);

  }
if (a=== false) { this.form.Alternatives.pop() //remove the last item
  }
else {}//just to avoid problems
}

Remember to update the HTML code to account for iterating over the 'form' variable.

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

Unable to retrieve data from response using promise in Angular 2?

I am struggling to extract the desired data from the response. Despite trying various methods, I can't seem to achieve the expected outcome. facebookLogin(): void { this.fb.login() .then((res: LoginResponse) => { this.acce ...

What is the best method for obtaining XML within typescript react in the bpmn-js/lib/Modeler?

After importing my BPMN XML in Model using importXML and setting bpmnModeler to bpmnModelerClone, I now need to retrieve the BPMN from bpmnModelerClone. How can I achieve this? Below is the code snippet showing how I imported XML and set bpmnModeler to bp ...

Execute an Angular 7 Single Page Application directly through the file:// protocol

I've been diving into tutorials on SPA and client-side routing, but I'm still struggling to grasp it fully. How can I configure the router to function without a web server? For example: file:///C:/cxr/CXR-WebViews/dist/CXR-WebViews/index.html#/p ...

Index beyond bounds of array

As I approach the completion of my assignment, I am encountering a challenge while attempting to create a map using a nested for loop. Below is the code segment along with the error message that I am facing: public void draw(){ System.out.println("Initia ...

The Angular API request is continuously retrieving data every single second

I recently inherited some Angular/ng-bootstrap code that included a table with static data, which was functioning perfectly. However, the requirement now is to fetch the data from an API call. In an attempt to modify it accordingly, I referred to an answer ...

Ways to merge two distinct arrays [Angular and Typescript]

I am faced with a task where I need to merge two array lists in order to create a new array list that contains all the values associated with a common UUID in both lists. The final list should include all the values linked to the UUID in each of the origin ...

Fetching data in VueJs before redirecting to a new page

Within the mounted function, I am creating an action that fetches data from a Rest API and populates my table in a Vue.js component mounted() { UserService.getProjects().then( (response) => { this.isProject = true; this.project ...

The current issue I am facing is that the option disabled with value="null" selected is not being shown on the screen. Instead, it should display as "Choose User Types"

https://i.sstatic.net/JqZ7O.png <select class="form-control" id="ddSelectaTopic" onchange="if(this.value==='') {this.style.color='#999'} else {this.style.color='#333'}" [(ngModel)]="us ...

The HTTP post method is not consistently triggering

Currently, I am in the process of developing a logout feature for angular (with a spring backend). The logout action is triggered by sending an HTTP post request to /auth/logout, where the endpoint invalidates the auth-token and refresh-token HTTP-only coo ...

Checking for Object Equality in TypeScript

I'm working on a TypeScript vector library and encountered my first failed test. The issue revolves around object equality in TypeScript/JavaScript, and despite searching through TypeScript's official documentation (http://www.typescriptlang.org ...

The cdkDropListSortingDisabled attribute is not recognized as a valid property for the cdkDropList directive in Angular Material

I'm trying to achieve a specific use case where I need to drag and drop data from one zone (div) to another. After some research, I discovered that angular/material2 with the cdkDropList API could help me accomplish this task. Using the copyArrayitem ...

Typescript React Union type

I have developed a Card component with two different variants: Wrapper and Dashboard. Each variant comes with its own set of props. export type DashboardProps = { variant: CardVariant.Dashboard, primaryText: string, secondaryText: string, icon: Ove ...

Is there a way to verify the selected navigation item in the console?

Need help with checking the selected navigation using console.log? export const navItems: NavData[] = [ { name: 'Book #1', url: '/book', icon: 'fa fa-book', children: [{ name: 'Book #2', ...

Encountered a timeout error of 2000ms while running tests on an asynchronous function within a service

Here is the service I am working with: class MyService { myFunction(param){ return Observable.create(obs => { callsDBfunc(param, (err, res) => { if(err) obs.error(err); ...

Tips for generating a fixed-length array from multiple arrays with different lengths, focusing on selecting items from each array according to their significance

In order to create a quiz, I am looking to extract 'questions' from various 'topic' arrays. These topics are selected based on the user's preference and are used to populate a question bank for a 20-question quiz. The topics rated ...

organize the values based on their priority using reactjs

I'm facing a challenge involving two arrays of objects: array1 and array2. I need to display only three values from both arrays, with priority given to array1. The requirements are as follows: if array1 contains 3 elements, all three should be shown. ...

Toggle the visibility of certain side menu items based on user authentication status

Using Angular 2, I created a website where I need to enable or disable certain sidebar components based on user login data. The user's login data is stored in JSON and a token is passed via Qwebchannel for authentication on localhost. My goal is to dy ...

Implementing the "$store" property within Vue components

Click here for a guide on how to type the $store property. Unfortunately, I've been encountering issues with it. In my Vue 2 project created using vue-cliI, I included a vuex.d.ts file in ./src directory but the $store property in my components still ...

Observable<void> fails to trigger the subscriber

I am currently facing a challenge with implementing a unit test for an Observable in order to signal the completion of a process. While there is no asynchronous code in the logout function yet, I plan to include it once the full logic is implemented. The m ...

Error in Angular 4: Undefined property 'replace' causing trouble

I've been trying to use the .replace() JavaScript function in Angular 4 to remove certain characters from a string. Here is the code snippet from my component: @Component({...}) export class SomeComponent implements OnInit { routerUrl: string = &apo ...