A comprehensive guide to using Reactive Forms in Angular

I need help understanding how FormGroup, FormControl, FormArray work in Angular.

The error message I'm encountering is:

Type '{ question: FormControl; multi: true; choices: FormArray; }' is not assignable to type 'AbstractControl'.
Object literal may only specify known properties, and 'question' does not 
exist in type 'AbstractControl'.ts(2322)

My attempt at using these controls:

survey: FormGroup;

results = {
  success:"",
  error:""
}

constructor(private fb: FormBuilder) { }

ngOnInit() {
  this.survey = new FormGroup({
    name: new FormControl(['My Quick Survey', Validators.required]),
    questionnaires: new FormArray([{
      question: new FormControl('Ready for a quick survey?'),  //error
      multi:true,
      choices: new FormArray([
        {text: new FormControl('Yes')},   //error
        {text: new FormControl('No')}    //error
      ])
    }])
  })

  console.log(this.survey)
}

Currently, I have structured my code like this:

survey = {
name:"My Quick Survey",
questionnaires:[{
  question:"Ready for a quick survey?",
  multi:true,
  choices:[
    {text:"Yes"},
    {text:"No"}
  ]
}]  
}

I am unsure how to resolve the error. Any guidance would be appreciated.

Thank you

Answer №1

For your FormBuilder implementation, consider giving this code a try:

this.survey = this.fb.group({
    name : ["My Quick Survey",[Validators.required]],
    questionnaires : this.fb.array([{
         question  : ["Ready for a quick survey?"],
         multi     : ["true"],
         choices   : [ "Yes"]
}])
});

In the following example

choices:[{text:"Yes"},{text:"No"}]
, you are attempting to create nested FormArrays. You can either use this.fb.array([]) again here or stick with the simpler approach using just FormControl.

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

Similar to AngularJS Component's "require" property, Angular Component also has an equivalent

In the process of updating a sizable Angular 1.6 App, we encounter numerous components that utilize 'require' to access the parent component's controller. The structure of an AngularJS component appears as follows: var tileTextbox = { ...

When sending an HTTP post request from an Angular frontend to an Express backend server, a 404

I am currently sending a request to an Azure function locally url = 'http://localhost:7071/api/saveGraphDataFlow' save(body) { let headers = new HttpHeaders() headers.append('Content-Type', 'application/json') return th ...

What is preventing this from functioning properly? (html/javascript)

I need help checking if this code is correct, as I am not very knowledgeable about HTML. I would appreciate it if someone could explain it to me in simple terms so I can understand. Here is the code: <input type="text" id="user" value=""> <inpu ...

What methods are available for generating a short-lived banner using JavaScript?

I recently entered this industry and am in the process of constructing a website. Utilizing HTML and CSS, I crafted a cookie notification banner. I am seeking guidance on how to ensure that it only appears once "every 24 hours for each user." I attempted ...

Printing Apex Oracle reports using Internet Explorer

I am facing a challenge with printing my page that contains two interactive reports. To enable printing, I have utilized a JavaScript function that triggers window.print(). I have incorporated CSS to adjust the layout of my tables when printed. @media pr ...

I prefer to avoid generating the document structure while parsing with JSOUP

Utilizing the Jsoup API to parse a section of HTML using the Jsoup.parse() method. However, during parsing, it includes the document structure in the HTML content. For Instance: <p><a href="some link">some link data</a> Some paragraph c ...

Error Type: TypeError when using Mongoose's FindOneAndUpdate function

I am encountering difficulties while trying to implement a findOneAndUpdate query. //UserController UserDAO ['findOneAndUpdate'](userId, {& ...

Loop through options in Vue.js and set a specific option as selected

When iterating through a list of objects, I am struggling to set the status of each object as selected by default. <template> <table class="table is-striped"> <thead> <tr> <th> ...

After 15 minutes of inactivity in the Angular project, the JWT (Json Web Token) token expires leading to the need for renewal or refresh

I have integrated a JWT token authentication service in my Angular project with an ASP.Net Core API as the backend. Here's how I set it up: Startup.cs public void ConfigureServices(IServiceCollection services) { services.AddAuthentication( ...

The functionality of json_encode seems to vary when applied to different PHP arrays, as it successfully encodes data for

My current challenge involves importing three arrays from PHP into JS using json_encode. Below is the code snippet I am currently working on: <?php $query2 = "SELECT * FROM all_data"; $result2 = $conn->query($query2); $bu = []; ...

Ways to modify the color of the legend text in a HighChart graph

Click here I am attempting to modify the color of the series legend text from black to any color other than black: $(function () { $('#container').highcharts({ legend: { color: '#FF0000', backgroundColor: '#F ...

Retrieving information from a data file by implementing a GraphQL Apollo Server within a NextJS application route

Currently working with Next.js 14 (app route), React, and the GraphQL Apollo framework. I have a JSON file containing data saved locally that I'd like to display using the server API. How can I make this happen? Below is the JSON structure I need to r ...

Render multiple checkboxes with values from an array of objects passed as a prop to a child component using a v

I am facing an issue with my Vue components 'Parent' and 'Child'. Each child component has a checkbox with a :checked prop. In the Parent component, I iterate through an array of objects and pass props to the child. Although I can emit ...

Top method for sending arguments when utilizing RxJS forkJoin

Hey there! I'm currently working on a service with three functions that I need to execute. To handle this, I've opted for using forkJoin as it allows me to take further action once all responses are received. One of the functions requires one par ...

What is the best way to assign a TypeScript type as the object type within an array of objects sourced from a different interface?

I am working with a generated interface that looks like this: export interface StaticPageLeftMenuV1 { id: string status: 'draft' | 'published' environments: ('dev' | 'staging' | 'production')[] ...

What is the process for passing an Object from JavaScript to an Action class in Struts 2?

Within my Action class, there exists an object of the class that is a POJO. public class ConfigureTspThresholdAction extends ActionSupport implements SessionAware, ModelDriven<GmaThresholdParameter>{ private Map<String,Object> session ...

Struggling with the transformation: Failed to find import "child_process" in TypeScript

I encountered an issue when trying to run my simple TypeScript project. I am receiving the following error: 'Error while transforming Could not resolve import "child_process".' You can see the error in this screenshot. This error occurs in my tsc ...

React Native Issue: The mysterious disappearance of the 'navigation.push' object

I am trying to navigate to List.js after clicking a button in the MainMenu.js file, but I keep encountering this error: TypeError: undefined is not an object (evaluating 'navigation.push') This snippet is from my App.js file import { StatusBar ...

Click the "Add" button to dynamically generate textboxes and copy the contents from each

I am working on a project where I have an Add button and 6 columns. Clicking on the Add button generates rows dynamically, which can also be deleted. My challenge is to copy the content of one textbox into another in 2 of the columns. This copying function ...

Tab-based Ionic 2 advertising campaign featuring banners

Is there a way to incorporate an advertisement banner image above the tabs in ionic 2? Any suggestions on how I can achieve this or create the banner in that specific position? ...