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

Ways to access a property within an object using TypeScript

Can you help me extract the "attributes" array from this object and store it in a new variable? obj = { "_id": "5bf7e1be80c05307d06423c2", "agentId": "awais", "attributes": [ // that array. { "created ...

"Trying to create a new project with 'ng new xxx' command resulted in error code -4048

Whenever I execute 'ng new projectName' in vs code, I encounter the following issue. ng new VirtualScroll ? Would you like to add Angular routing? Yes ? Which stylesheet format would you like to use? SCSS [ http://sass-lang.com ] CREATE Vir ...

Issue with Angular ngFor: displaying only one name instead of all names in the loop

In my component.ts file, I have retrieved this data from an API call: [ [ { "name": "name one", "desc": "something here", }, { "name": &quo ...

Refine the search outcomes by specifying a group criteria

I have a scenario where I need to filter out service users from the search list if they are already part of a group in another table. There are two tables that come into play - 'group-user' which contains groupId and serviceUserId, and 'gro ...

Combining type inference validation and authentication middleware in Express routes can be a powerful way to enhance security and ensure

I am struggling to grasp how types are automatically determined in Express routes when utilizing multiple middlewares. To conduct validation using zod, I have employed the middleware package express-zod-safe, although a similar issue arose with alternativ ...

Utilizing arrayUnion function in Firestore with Angular

My journey to learn Firestore has hit a roadblock. The documentation on AngularFire and FieldValue hasn't been much help. Every time I try to use FieldValue, it throws an error saying "FieldValue does not exist." const userRef = this.firestore.collect ...

Tips for obtaining type narrowing for a function within a mixed array

In my coding adventure, I have crafted a brilliant match function. This function is designed to take a value along with an array of [case, func] pairs. The value is then compared to each case, and if a match is found, the associated func is executed with t ...

Handling exception type in child_process exec method - NodeJS with Typescript integration

Check out this sample code: const execPromise = util.promisify(exec); try { const { stdout } = await execPromise(cliCommand); } catch (error) { if (error instanceof S3ServiceException) { // error message is not handled correctly console ...

Encountered a syscall spawn git error while running npm install command

I recently attempted to execute npm install and encountered the following problems: Even after attempting to clear cache forcibly, installing git, and updating node, none of these solutions proved effective. Above is the specific error message I received ...

minimize the size of the image within a popup window

I encountered an issue with the react-popup component I am using. When I add an image to the popup, it stretches to full width and length. How can I resize the image? export default () => ( <Popup trigger={<Button className="button" ...

The function of type 'PromiseConstructor' is not executable. Should 'new' be added? React TypeScript

.then causing issues in TypeScript. interface Props { type: string; user: object; setUserAuth: Promise<any>; } const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault(); if (type === "signup" ...

For each array element that is pushed, create and return an empty object

I am encountering an issue with an array where the objects are being generated by a push operation within a function. Despite successfully viewing the objects directly in the array, when I attempt to use forEach to count how many times each id uses the ser ...

Can a string array be transformed into a union type of string literals?

Can we transform this code snippet into something like the following? const array = ['a', 'b', 'c']; // this will change dynamically, may sometimes be ['a', 'e', 'f'] const readonlyArray = arr ...

I have successfully implemented useLazyQuery in a functional component, but now I am looking to integrate it into a class component. Can you provide guidance on how to achieve

Recently, I encountered an issue with my functional component that contains 3 checkboxes and 1 button. I utilized the useLazyQuery hook to ensure that my query was only sent upon clicking the button. However, a major drawback is that my component re-rend ...

Implement a nested feature within the Accordion component

I am currently working on a project using Next.js and TypeScript. Within this project, I have implemented an accordion component as shown below: import React, { useEffect, useState } from 'react'; import classes from './Accordion.module.scss ...

Having difficulty testing an Angular/NGXS action that triggers after an unsuccessful API request

Struggling with writing tests for an NGXS action that calls an http request? Want to add tests for both successful and failed requests? Here is the code for my Action: @Action(SearchChuckNorrisJokes) searchChuckNorrisJokes({ getState, setState }: StateCo ...

Error: Microsoft.AspNetCore Client Side Rendering Services encountered a critical issue

We are working on an Asp.net core 2.1 +Angular 6 application. Within our Start.cs file, the following code snippet is present: app.UseSpa(spa => { // To learn more about options for serving an Angular SPA from ASP.NET Core, ...

Creating a layout of <video> components in vue.js, complete with the ability to rearrange and resize them through drag and drop functionality

Despite trying numerous libraries and Vue.js plugins, I have yet to find one that meets all of my requirements. I am in need of creating a grid of video HTML elements that are draggable and resizable with a consistent aspect ratio of 16:9. Additionally, I ...

Service is not designed as a singleton within the MatDialog module

Whenever I launch a Mat Dialog popup in Angular Material and try to access a singleton service, the service appears to be a new instance within the dialog rather than the singleton service utilized throughout the application. Although I am familiar with w ...

Is it possible to use the provide() method with a string in Angular 2 when writing

I am attempting to utilize a String as a token for providing instead of a class: app.RandomComponent = ng.core .Component({ selector: "randomComponent", template: "Component!", providers: [ ng.core.provide("Stuff", ...