Angular 4: The types "AbstractControl" do not have the property "push" or "controls" available

I tried implementing the code found at http://plnkr.co/edit/yV94ZjypwBgHAlb0RLK2?p=preview, but I am encountering errors related to push and controls.

I followed the instructions provided, but I am unsure of what is causing the issue.

import { Component } from '@angular/core';
import { ViewController,Platform } from 'ionic-angular';
import { FormBuilder,FormGroup,Validators,FormControl,FormArray } from '@angular/forms';

@Component({
  selector: 'filter-vendor',
  templateUrl: 'filter-vendor.html'
})

export class FilterVendorPage {




  questions = [{id:1,text:'Question 1', answers:[{id:1},{id:2}]},{id:2,text:'Question 2', answers:[{id:11},{id:22}]}]
  surveyForm:FormGroup;



  constructor(
    private viewCtrl: ViewController, 
    private formBuilder:FormBuilder
     ){


      this.surveyForm=this.formBuilder.group({
        question:formBuilder.array([])
      })

      for(var i=0;i<this.questions.length;i++){
          let question=formBuilder.group({
            question_id:[this.questions[i].id,Validators.required],
            answer_id:formBuilder.array([])
          });
          this.surveyForm.controls['questions'].push(question);
      }
}


   onChange(id, isChecked, index) {

    const answers = <FormArray>this.surveyForm.controls.questions.controls[index].controls.answer_ids

    if(isChecked) {
          answers.push(new FormControl(id))
        } else {
          let idx = answers.controls.findIndex(x => x.value == id)
          answers.removeAt(idx)
    }
  }

}

I would appreciate any assistance in resolving this issue. Thank you in advance.

Answer №1

When TypeScript is checking types, it may prompt an error. To resolve this, you will need to cast your control to a FormArray. In order to do so, make the following changes:

1)

this.surveyForm.controls['questions'].push(question);

should be changed to

(<FormArray>this.surveyForm.controls['questions']).push(question);

or

(this.surveyForm.controls['questions'] as FormArray).push(question);

or

(this.surveyForm.get('questions') as FormArray).push(question);

2)

const answers = <FormArray>this.surveyForm.controls.questions.controls[index].controls.answer_ids

should be changed to

const answers = this.surveyForm.get(['questions', index, 'answer_ids']) as FormArray;

or

const answers = this.surveyForm.get(`questions.${index}.answer_ids`) as FormArray;

Forked Plunker

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

The element 'swiper-container' is not recognized in version 9

Recently upgraded to swiper v9.0.3 and encountered the issue 'swiper-container' is not a recognized element: If 'swiper-container' is an Angular component, ensure it is included in the '@Component.imports' of thi ...

How can I enable SCSS/SASS support on Parcel-Angular5?

I started a project using angular cli. My intention is to incorporate scss into the project. In the terminal of WebStorm, I entered : ng set defaults.styleExt scss I proceeded by renaming all the .css files to .scss and adjusted the imports accordingly ...

The Angular @HostListener beforeunload Event is a powerful way to handle

I've implemented the following code snippet in my main app.component.ts file within my Angular 17 project: @HostListener("window:beforeunload", ["$event"]) onTabClose($event: BeforeUnloadEvent) { $event.preventDefault(); ...

Navigating through Firebase after login

Encountering an issue with navigating to the register page using a firebase authentication promise. Instead of displaying only the register page, both the login page and register page are shown simultaneously: Login page with social buttons Register page ...

Setting up angular-cli project for rc5- Step by step guide

Trying to integrate angular-cli with angular 2 rc5 but facing challenges: The issue of 'Promise' not being found After attempting to install 'npm install -g angular-cli@webpack', typings did not get installed, resulting in WebStorm un ...

Implementing Express.js allows for the seamless casting of interfaces by the body within the request

I have created a similar structure to ASP.NET MVC and uploaded it on my github repository (express-mvc). Everything seems fine, but I am facing an issue with casting the body inside the request object to match any interface. This is what I am aiming for: ...

obtain data from an array using Angular 5

i need assistance with retrieving values from an array. Below is my code snippet: this.RoleServiceService.getRoleById(this.id).subscribe(data => { this.roleData.push(data['data']); console.log(this.roleData); }) however, the resulting ar ...

Inefficiency in POST method prevents data transmission to MongoDB

I've developed a MERN application and now I'm testing the backend using the REST client vscode extension. This is how it looks: `POST http://localhost:4000/signup Content-Type: application/json { "email": "<a href="/cdn-cgi ...

A unique directive that showcases both default and custom errors sequentially

In my project, I am facing a challenge where I need to compare the input text with a series of inbuilt errors such as required, minlength, maxlength, and pattern. Additionally, I also need to validate the input against a custom condition using a Custom Val ...

Creating a Modal using Typescript with NextJS

Currently, I'm working on creating a modal within my app using NextJS with Typescript. Unfortunately, I've been struggling to eliminate the warning associated with my modal selector. Can someone provide guidance on how to properly type this? cons ...

What are the steps for setting up Angular IDE on Ubuntu?

I am new to angular2 and I'm having trouble installing the angular IDE on my system. When I try to install it using npm, I encounter errors. Command : - npm install -g angular-ide Error Message:- npm WARN deprecated <a href="/cdn-cgi/l/email-p ...

Adding a unique font to the themeprovider within styled components: A step-by-step guide

In the process of developing a React application using material-ui styled-components along with TypeScript. The task at hand is to incorporate a custom font into my styled components, but I'm facing challenges in making it functional. My initial ste ...

Utilizing Emotion CSS to incorporate images into buttons

I'm trying to add some style to two buttons, Up and Down, by using emotion CSS but I'm having trouble. Currently, I typically style my elements within a function. Is there a way for me to accomplish this with emotion CSS? I checked out but still ...

Creating a hyperlink to a subdomain in TypeScript Execution File

I am seeking to add a link directing to a subdomain in the navigation bar of a react theme. Although I feel a bit hesitant about asking for help on something seemingly simple, I have struggled to find any relevant examples online to assist me. Below is the ...

An issue arises in Angular 17 where the view does not refresh when using setInterval, accompanied by the NG0500

I am currently working on a countdown timer feature where I want to continuously update the 'seconds' value in real-time, but I'm facing an issue with the UI not reflecting these updates. Whenever I attempt to implement this without utilizi ...

Error in Angular 6: String provider is missing from the NullInjector

Parent class import { BadRequestError } from './../common/bad-request-error'; import { NotFoundError } from './../common/not-found-error'; import { AppError } from './../common/app-error'; import { Http } from '@angular/ ...

What is the best way to transfer information from a child Angular app to a parent non-Angular app

If I have a plain JavaScript parent application with a child Angular application, how can I notify the parent application of any data changes in the child Angular application? The child application is loaded in a div, not in an iframe. ...

Using two type arguments, create a feature selector with ngrx

Currently, I am delving into the world of ngrx with Angular v6.0.9 and AngularCLI v6.0.8. In an example application, there is a demonstration on creating a root level createFeatureSelector with two type arguments: example-app/app/reducers/index.ts ..... ...

Invoke a method in an Angular 2 component using an HTML event

Can an angular component method be invoked using an HTML event? <shape onclick="myMethodInParentComponent()" > I am unable to use (click) as shape is not recognized by Angular. Shape also contains several unknown sub elements making it impractical ...

Should the User Id be retrieved within the ngOnIt() function?

Is it considered incorrect to access the User Id within the ngOnIt() method using this.afAuth.auth.currentUser.uid;? I am encountering an issue where uid is undefined when I reload the page, although it works correctly after logging in or being redirect ...