Building interactive forms in Angular 6

I want to design a dynamic form that creates a new form when the AddNew button is clicked.

In my TypeScript (ts) file, I have the following code:

    addinfoForm: FormGroup;
  infoNameList: FormArray;
  infoModel: Productdetail;

  constructor(private fb: FormBuilder, private router: Router, private tokenService: TokenstoreService) { }

  ngOnInit() {
    this.InfoForm();
  }

  /**
   * AddInfoForm
   */
  public InfoForm() {
    this.addinfoForm = this.fb.group({
      infoName: this.fb.array([this.CreateInfoName()])
    })
    this.infoNameList = this.addinfoForm.get('infoNames') as FormArray;
  }

  public CreateInfoName(): FormGroup {
    return this.fb.group({
      infoName: ['', Validators.compose([Validators.required])]
    });
  }

  public AddInfoName() {
    this.infoNameList.push(this.CreateInfoName());
  }

  public RemoveInfoName(index: number) {
    this.infoNameList.removeAt(index);
  }

I have used this code in the HTML as well:

        <div class="panel-content">
          <form class="form-line" [formGroup]="addinfoForm" (ngSubmit)="AddRole()">
                <div formArrayName="infoNameList">
                    <div class="description" *ngFor="let name of addinfoForm.controls; let NameIndex=index" [formGroupName]="NameIndex">
                    <div [formGroupName]="i" class="row">
                        <label class="form-line">  Name:   </label>
                        <input style="margin-right: 50px;" class="form-line" pInputText id="pFaName" formControlName="Name">
                        <app-filederrors [form]="addinfoForm" 
                            field="pFaName"
                            nicename="Name">
                        </app-filederrors>
                    </div>
                    </div>
            </div>
        </form>
        <button (click)="AddInfoName()">Add New </button>
              <div class="button">
                  <button pButton type="button" label="REgister" (click)="AddCat()" [disabled]="!addinfoForm.valid" class="ui-button-rounded"></button>
                  <button pButton type="button" label="Cencel" class="ui-button-rounded ui-button-danger"></button>
              </div>
    </div>

However, upon clicking the button, I encounter the following error:

AddinfoComponent.html:21 ERROR TypeError: Cannot read property 'push' of null at AddinfoComponent.push../src/app/admin/admin/dashboard/productinfo/addinfo/addinfo.component.ts.AddinfoComponent.AddInfoName (addinfo.component.ts:41)

What is the best way to resolve this issue?

Answer №1

Perhaps consider using get('infoName') instead of get('infoNames').

  constructor() {
    this.infoForm = this.fb.group({
      infoName: this.fb.array([this.createInfoName()])
    });
    this.infoNameList = this.infoForm.get('infoName') as FormArray;
  }

Answer №2

One issue that needs to be addressed is the initialization of the infoNameList property, which is currently declared but not yet initialized, resulting in a null value.

To resolve this problem, simply follow these steps:

ngOnInit() {
    this.infoNameList = this.fb.array([]);
    this.createInfoForm();
}

Answer №3

incorrect label should read infoName

function BasicInfoForm() {
    this.addInfoForm=this.fb.group({
      infoName:this.fb.array([this.createInfoName()])
    })
    this.infoNameList=this.addInfoForm.get('infoName') as FormArray; // <- formerly infoNames
}

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

AngularJS Datepicker - calendar dropdown does not update when the model changes

I've been facing a challenge with the AngularJs datepicker in my project for some time now. Within my application, users have the option to either manually select a date using the calendar or click on "This Month" to automatically set the date to the ...

Issue: ParserError encountered due to a Syntax Error found at line 1, column 32

As a beginner in programming, I am encountering an issue. When I run "npm run build" in the Terminal to compress my project in React.js, I encounter this error. Interestingly, I have previously created another project without facing this problem, and I can ...

Different combinations of fields in Typescript types

Take a look at this defined type: type MyType = | { a: number } | { b: number } | { c: number } | ({ b: number } & { c: number }); The goal is to prevent the combination of 'a' with either 'b' or 'c'. const o1: ...

Convert the PHP datetime and timezone function to a JavaScript function

I have a helpful function in my solution that I'd like to share: public static function formatTime($time, $timezone) { $timezone = new \DateTimeZone($timezone); $time = $time->setTimezone($timezone); return \Locale::getDefaul ...

Having trouble locating the type definition file for '@types' while working with Ionic 4 and Angular 7

Recently, I made the transition in my ionic 4 project to utilize angular 7. While everything seems to be functioning correctly in debug mode, I encountered an issue when attempting to compile for production using the command 'ionic cordova build andro ...

Is there an Angular directive that can replicate a mouseenter event?

Is there a way to simulate a mouseenter event with a directive? I have been searching for a directive that can simulate a mouseenter event, but all I have found so far is one that binds a function to mouse over or karma tests for simulating mouse over. W ...

The inline style in Angular 2 is not functioning as expected when set dynamically

Having a small dilemma... I'm trying to apply an inline style within a div like this: div style="background: url(..{{config.general.image}})"></div Oddly enough, it was functioning in beta 16 but ever since the RC1 upgrade, it's no longer ...

Is there a way to integrate a snap carousel in a vertical orientation?

I am looking to make a List utilizing the snap carousel component, but I'm having trouble getting it set up. Can anyone help me with this? ...

Is there a way for me to access the names of the controls in my form directly from the .html file?

I have a list where I am storing the names of my form controls. In order to validate these form controls, I need to combine their names with my code in the HTML file. How can I achieve this? Below is my code: .ts file this.form = this.formBuilder.group({ ...

Beginner Query: What is the method for retrieving this data in JavaScript?

I'm struggling with accessing a specific value in an Object in JavaScript for the first time. The JSON I'm working with is structured like this: { "payload":{ "params":{ "switch:0":{ &q ...

Is there a way for a function to be executed without being detected by surveillance?

Here's the Component I'm working with: @Component({ selector: 'app-signup', templateUrl: './signup.component.html', styleUrls: ['./signup.component.scss'] }) export class SignUpComponent implements OnInit ...

Exploring the best practices for integrating Bootstrap into a Webpack and Angular2 project

I am looking to incorporate Bootstrap into my Angular2 project, including both the CSS and JS files. What is the best way to include these files in the project to ensure webpack functions properly? In the previous version using systemjs, it was included i ...

"Encountering issues with the production build of angular2-flash-messages

I have integrated angular2-flash-messages into my Angular (4) application. I included it in app.module.ts as shown below: import { FlashMessagesModule } from 'angular2-flash-messages'; imports: [ FlashMessagesModule, ], Everything works f ...

Experience the dynamic bouncing marker feature in Next.js React-Leaflet with the powerful tool Leaflet.SmoothMarkerB

I'm a beginner in front-end development and I'm attempting to create a bouncing marker in React-leaflet using the leaflet.smooth_marker_bouncing plugin version 1.3.0 available at this link. Unfortunately, I couldn't find enough documentation ...

Synchronize JSON data with the Document Object Model (DOM

My current project is built using React, where I am rendering the page dynamically based on JSON data. The page consists of various component types, ranging from images to text content. Each component includes a delete option, allowing users to change im ...

Encountering an issue with Next.js React SSR using styled-jsx: unable to access the 'state' property as

I've come across a problem that I can't seem to figure out. Despite my attempts to search for a solution here, I haven't been able to help myself. I'm new to javascript and react, so please bear with me. Issue: I'm using React (1 ...

Using JavaScript/jQuery to Set a Timer for Animation with Google Maps Markers

After clicking a marker on a Google map, I've managed to make it bounce with the following code. However, I'm looking for a way to stop the animation after 2 seconds. Is there some kind of timer function that I can incorporate? Here's the ...

Retrieve all elements from an array using jQuery

How do I extract all the elements from the array outside of the function? $.each(Basepath.Templates, function(i){ templateArray = new Array({title: Basepath.Templates[i].Template.name, src: 'view/'+Basepath.Templates[i].Template.id, descri ...

Ensuring Date Data Integrity with HTML5 Validations

I need to set up validation for a mobile website that includes two input fields. The first field should validate that the value is not later than today's date, while the second field should validate that it is not later than one year in advance of the ...

The challenge of incorporating Laravel, Vue, and JavaScript into a Blade template

It may seem like a silly question, but I am struggling to find a solution. My goal is to load a Vue component and JS file into a blade view. When I include the following: <script src="{{ asset('js/app.js') }}"></script> <script sr ...