Having trouble getting access to FormArray content for validation due to receiving null or undefined errors

CSS Tricks

<form [formGroup]="newMovieForm">
   <ng-container formArrayName="actors">
     <ng-container *ngFor="let actor of (actors['controls'] || []) ; let i = index">
        <div [formGroupName]="i">  
            <input type="text" class="form-control" placeholder="First Name" formControlName="firstName" required>
                 <span *ngIf="newMovieForm.controls['actors']?.get(i).controls['firstName'].errors?.['hasSpaces']">class="text-danger">
                     Field is required!
                </span>

JS Form Building Logic

this.newMovieForm = this.fb.group({
      // These are the essential controls
      movieName: ['', [Validators.required, CustomValidators.noSpaceAllowed]],
      yearOfRelease: ['', [Validators.required]],
      description: ['', [Validators.required]],
      rentalCost: ['', [Validators.required, CustomValidators.onlyNumbersAllowed]],
      imageUrl: ['', [Validators.required, CustomValidators.noSpaceAllowed]],
      actors: this.fb.array([]),
      userReviews: this.fb.array([])
    })

Advanced Form Group Methodology in JS

addActor() {
    const actor = this.fb.group({
      firstName: ['', [Validators.required, CustomValidators.noSpaceAllowed]],
      lastName: ['', [Validators.required, CustomValidators.noSpaceAllowed]],
      gender: ['', [Validators.required]],
      age: ['', [Validators.required]],
      imageUrl: ['', [Validators.required, CustomValidators.noSpaceAllowed]]
    });
    this.actors.push(actor);
  }

Struggling to Access Validators in Angular Forms

I am attempting to access the firstName validators within the actor formGroup for specific error handling. There are a couple of issues causing confusion:</p>
*ngIf="newMovieForm.controls['actors']?.get(i).controls['firstName'].errors?.['hasSpaces']

<ol>
<li><p>Uncertain about whether the above syntax accurately validates the field</p>
</li>
<li><p>Despite including null checks like ? or checking for undefined, still facing Object is possibly "null" or "undefined" warning.</p>
</li>
</ol>
I prefer not to disable strict mode, seeking solutions for this problem.

Answer №1

<ng-container formArrayName="performers">
 <ng-container *ngFor="let performer of (performers['actors'] || []) ; let j = index">
    <div [formGroupName]="j">  
        <input type="text" class="form-control" placeholder="Last Name" formControlName="lastName" required>
             <span *ngIf="newMovieForm.hasError('hasSpaces','actors.'+j+'.lastName')">class="text-danger">
                 Please fill out this field!
            </span>

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

Angular 6 - Defining two components with several modules nested within each other

There are two components, C1 and C2. Each component has its own module file. How can I declare C1 in C2 in Angular 6? // Module 1 @NgModule({ imports: [], exports: [], declarations: [ ComponentX, ComponentY ], providers: [] }) // Module 2 @NgModule ...

How can I make my webpage fill the entire width of an iPhone screen when in landscape mode using Angular or React?

While testing my website on my iPhone, I noticed a significant gap appearing on either side of the app in landscape view in Safari. Is there a solution to fix this issue? The problem occurs in both Angular and React applications, examples of which are disp ...

Error Found: Unexpected Colon (:) in Vue TypeScript File

Important Update: After thorough investigation, it appears that the issue is directly related to the boilerplate being used. As a temporary solution, it is recommended not to extract the TypeScript file but keep it within the .vue file for now. In a sim ...

Encountering npm3 installation errors with typyings in Angular 2?

Each time I try to sudo npm install Angular 2 modules, everything updates and installs correctly. However, I encounter the following error when the typings install is attempted: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0 ...

Tips for selecting the best className type for material-ui components

Currently, I am integrating material-ui into a react app that is built using typescript. Within the material-ui framework, there is a feature called withStyles which allows styles to be injected into a component through its className. However, I am facing ...

Exploring Query Parameters in Angular 4

Is it possible to generate a custom URL in Angular 4? For instance: http://localhost:4200/#/page/page2/6/abc/1234 Currently, I am utilizing query parameters like this: this.router.navigate(['page/page2/' + row.id],{ queryParams: {'name&a ...

Methods for bypassing a constructor in programming

I am working on a code where I need to define a class called programmer that inherits from the employee class. The employee class constructor should have 4 parameters, and the programmer class constructor needs to have 5 parameters - 4 from the employee c ...

Leveraging moment.format Function in Angular within an HTML Context

Is there a way to implement the moment.format method in HTML? Currently, I am utilizing the toLocaleDateString method to showcase an array of dates: <ng-template let-event> <div>{{event.date.toLocaleDateString(' ...

Introduce a specialized hierarchical data structure known as a nested Record type, which progressively ref

In my system, the permissions are defined as an array of strings: const stringVals = [ 'create:user', 'update:user', 'delete:user', 'create:document', 'update:document', 'delete:document&ap ...

Struggling with setting up a search bar for infinite scrolling content

After dedicating a significant amount of time to solving the puzzle of integrating infinite scroll with a search bar in Angular, I encountered an issue. I am currently using Angular 9 and ngx-infinite-scroll for achieving infinity scrolling functionality. ...

Utilizing the functionalities provided by node.js, I came across an issue and sought out a solution for the error message "TypeError: __WEBPACK_IMPORTED_MODULE_3_fs__.writeFile is not a function"

I have created a project centered around {typescript, react, electron, gaea-editor}. During an event, I utilized fs.writeFile() but encountered an error. The specific error message was: TypeError: __WEBPACK_IMPORTED_MODULE_3_fs__.writeFile is not a functi ...

Changing the generic type's constraint type in TypeScript to have more flexibility

I have developed a utility type named DataType that takes in a parameter T restricted to the type keyof MyObject. When the key exists in MyObject, DataType will return the property type from MyObject; otherwise, it will simply return T. interface MyObject ...

Troubleshooting: Issue with reloading in MERN setup on Heroku

I successfully deployed my MERN stack application on Heroku using the following code: import express from "express"; import path from "path"; const app = express(); const port = process.env.PORT || 5000; app.get("/health-check&qu ...

In order to maintain a custom tooltip in an open state until it is hovered over, while also controlling its

When hovering over the first column of the table, a tooltip will appear. Within each material tooltip, I would like to include a button at the bottom right after the JSON data. When this button is clicked, it should open an Angular Material dialog. <ng ...

working with JSON arrays in angular framework

Is there a way to print a specific value from an array in typescript? Below is the code snippet in typescript that I'm working with: import { AngularFirestore } from '@angular/fire/firestore'; export class ProfileComponent implements OnInit ...

fesm2020/ngx-translate-multi-http-loader.mjs:2:0-41 - Whoops! Looks like the module couldn't be located

After updating my ngx-translate-multi-http-loader from version 8.0.2 to 9.3.1, I encountered a module not found error. The error message is as follows: ./node_modules/ngx-translate-multi-http-loader/fesm2020/ngx-translate-multi-http-loader.mjs:2:0-41 - Err ...

An issue has occurred: it seems that the property cannot be accessed because `this.child` is undefined

Is there a way to call the function "initMap" that is defined in the child component "UpdatePinComponent", from the parent component named "ApiaryComponent"? Below is a snippet of the TypeScript code from the parent component: import { AfterViewInit, Compo ...

Node.js server only supports cross-origin requests for protocol schemes when working with an Angular front end

Struggling to configure CORS on a local site hosting a Node.js server and an Angular client. Encountering the following error: Access to XMLHttpRequest at 'localhost:3000/api/v1/users' from origin 'http://localhost:4200' has been bl ...

Reusing methods in Javascript to create child instances without causing circular dependencies

abstract class Fruit { private children: Fruit[] = []; addChild(child: Fruit) { this.children.push(child); } } // Separate files for each subclass // apple.ts class Apple extends Fruit { } // banana.ts class Banana extends Fruit { } ...

Encountering a navCtrl problem in Ionic 3 while attempting to utilize it within a service

I am currently working on a feature to automatically route users to the Login Page when their token expires. However, I am encountering an issue with red lines appearing under certain parts of my code. return next.handle(_req).do((event: HttpEvent< ...