There was an issue: Control with the name 'name' could not be located

Whenever I submit the form and try to go back, an error pops up saying "ERROR Error: Cannot find control with the name: 'name'". I'm not sure what I might be missing. Do I need to include additional checks?
Below is my HTML file:

<div class="col-xs-12">
  <form [formGroup]="sectionForm" novalidate class="form">
    <div class="col-xs-12">
      <div class="col-sm-6">
        <fieldset class="form-group">
          <label>
            Section Name
          </label>
          <input type="text" formControlName="name" class="form-control">
          <div class="invalid-feedback" *ngIf="sectionForm.controls['name']?.errors && submitted">
                        <span *ngIf="sectionForm.controls['name']?.errors.required">
                            Section name is required.
                        </span>
          </div>
        </fieldset>
        <fieldset class="form-group" *ngIf="!subject">
          <label>
            Choose a Subject
          </label>
          <select class="custom-select" placeholder="Select Subject" formControlName="subjectId" >
            <option *ngFor="let subject of subjects" [value]="subject._id">{{ subject?.name }}</option>
          </select>
          <div class="invalid-feedback" *ngIf="sectionForm.controls['subjectId'].errors && submitted">
                    <span *ngIf="sectionForm.controls['subjectId'].errors.required">
                        Subject is required.
                    </span>
          </div>
        </fieldset>
        <button class="btn btn-primary" type="submit" (click)="create()">Submit</button>
      </div>
    </div>
  </form>
</div>

This is my Typescript file:

export class SectionsCreateComponent implements OnInit {
  program;
  submitted;
  test;
  section;
  sectionForm: FormGroup =new FormGroup({});
  isBusy;
  chapter;
  subject;
  subjects = [];

  
  ngOnInit() {
    if (!this.program) {
      this.router.navigate(['program']);
    } else {
      this.refresh();
    }
  }

  refresh() {
    this.getSubjects();

    
    let testId=this.activatedRoute.snapshot.params['testId'];
    
    if (this.section) {
      this.sectionForm = this.fb.group({
        'name': [this.section.name, Validators.compose([Validators.required])],
        'testId': [testId, Validators.compose([Validators.required])],
        'subjectId': [this.section.subjectId, Validators.compose([Validators.required])]
      });
    } else {
      this.sectionForm = this.fb.group({
        'name': ['', Validators.compose([Validators.required])],
        'testId': [testId, Validators.compose([Validators.required])],
        'subjectId': [this.subject ? this.subject._id : '', Validators.compose([Validators.required])]
      });
    }
  }

  getSubjects() {
    this.subjectService.list(this.program).subscribe(
      data => this.subjects = data.data
    );
  }

  create() {
    this.submitted = true;

    if (!this.sectionForm.valid) {
      return;
    }
    let testId=this.activatedRoute.snapshot.params['testId'];
    let programId=this.program;

    this.isBusy = true;
    if (this.section && this.section._id) {
      const reqObject = {
        ...this.sectionForm.value
      };
      reqObject._id = this.section._id;
      this.testsService.updateSection(reqObject).subscribe(
        data => {
          this.alertService.showSuccess('Success', 'Program updated successfully');
          this.dataService.setInterComponentsData({subject: this.subject, program: this.program, chapter: this.chapter, test: this.test});
          this.router.navigate([`tests/${testId}/${programId}/sections/list`]);
        }
      );
    } else {
      this.testsService.createSection(this.sectionForm.value).subscribe(
        data ...

I've also attempted:

'name': [this.section this.section.name ? this.section.name : '', Validators.compose([Validators.required])],

But I'm still encountering errors. If there's something I'm overlooking, any help would be appreciated.

Answer №1

It appears that when !this.program routes to a different component, the program value may not be fetched in time for the form controls to render correctly. Initially, the form controls are not defined:

sectionForm: FormGroup = new FormGroup({});

To address this issue, you can use *ngIf to conditionally render the form:

<form *ngIf="program" [formGroup]="sectionForm" novalidate class="form">
 . . 
</form>

Alternatively, you can create a formGroup instance within the ngOnInit lifecycle hook:

sectionForm: FormGroup;

ngOnInit(){

 this.sectionForm = this.fb.group({
    'name': ['', Validators.compose([Validators.required])],
    'testId': ['', Validators.compose([Validators.required])],
    'subjectId': ['', 
    Validators.compose([Validators.required])]
    });

    . . .

   }

    

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

Incorporating External JavaScript and CSS specifically for a single component

In my Angular 4 application, I have a specific component that requires the use of a js and css file. While most guidelines suggest placing these files in the Index.html file, I prefer to only load them when this particular component is accessed, not on e ...

I've been working on setting up a navbar in React/typescript that links to various routes, but I've hit a snag - every time I try to create a link

import React from 'react' import { Link } from 'react-router-dom' export default function NavBar() { return ( <div className='NavContainer'> <link to='/home'>Home</link> <l ...

Issue: The component factory for GoogleCardLayout2 cannot be located

Recently I've been working on an Ionic 3 with Angular 6 template app where I encountered an issue while trying to redirect the user to another page upon click. The error message that keeps popping up is: Uncaught (in promise): Error: No component fac ...

Encountering issues with Typescript when providing parameters for res.status().json()

I've recently started using Typescript and I'm still in the learning process by converting some existing JS code to TS. In my code: res.status(200).json({ user: data.user }) I encountered a red squiggly underline under user:data.user ...

Although the karma test was successful, an error was encountered when running the npm test

While working with https://github.com/AngularClass/angular2-webpack-starter, I encountered an issue. When I navigate to the project directory and execute: karma start I receive the following output: SUMMARY: ✔ 0 tests completed However, when I run: np ...

The deployment on Heroku is encountering issues due to TypeScript errors related to the MUI package

As someone relatively new to TypeScript and inexperienced in managing deployments in a production setting, I've been working on a project based on this repository: https://github.com/suren-atoyan/react-pwa?ref=reactjsexample.com. Using this repo has a ...

JavaScript Library function in Angular Component throwing Type Error: Function is Not Recognized

I created a custom Javascript library to group together essential functions that many Angular Components require. The library called calcs.js includes functions like this: function calculateCosts(object) { do some stuff..... return answer; } To use t ...

Error TS2322: Type 'Partial<T>' is not assignable to type 'T'

I'm struggling to articulate my problem, so I think the best way to convey it is through a minimal example. Take a look below: type Result = { prop1: { val1: number, val2: string }, prop2: { val1: number } }; f ...

Having trouble retrieving files from an Angular2 service

I am facing an issue in creating an Angular2 service for downloading files from the server. I have a table where each record represents a single file. When clicking on a specific record, the download method is called: download(r: FileObject) { this.re ...

Instructions on setting a photo as a background image using a text-based model

I'm a beginner with Angular so I may have a simple question. I am using an image from the Google API, which is not a URL. How can I set this image as the background-image in a CSS tag that only accepts URIs? Thank you! ...

Is there a way to achieve a seamless compilation in TypeScript?

Hopefully this is straightforward! TypeScript Latest version: 1.9.0-dev.20160512 (can be installed using npm install -g typescript@next as suggested by @basarat) Node v5.11.0 Windows 10.0.10586 First file: u1c.ts import * as u1u from "./u1u.ts" let p = ...

How can one dynamically update a page in Angular when the path is changed?

I am facing a pagination issue in Angular. Here is my HTML code: <!-- A div element for pagination part at the bottom of the page --> <div style="margin-left: 50%; margin-top: 20px; margin-bottom: 20px"> <ul class="paginat ...

Is it possible for a Node.js/Express server to securely handle all UTF-8 characters?

At the moment, my setup involves a node server running Express that is connected to a PostgreSQL database with UTF-8 encoding support. In terms of frontend, I'm using Angular which has built-in measures for preventing unsafe injection. I am curious i ...

Ensuring TypeScript's strict null check on a field within an object that is part of an

When using TypeScript and checking for null on a nullable field inside an object array (where strictNullCheck is set to true), the compiler may still raise an error saying that 'Object is possibly undefined'. Here's an example: interface IA ...

I am facing the dilemma of having an identical button appearing in two separate locations. How can I determine which button has been clicked?

I am currently using ng2-smart-table and have implemented a custom filter with the same button in both filters. However, I am unsure of how to determine which button is being clicked. https://i.stack.imgur.com/b1Uca.png Below is the component code for th ...

Understanding Angular 2 Testing: The Ultimate Guide to Implementing Async Function Calls

What is the purpose of using the async function in the TestBed when testing Angular 2? Is there a specific scenario where it should be used? beforeEach(() => { TestBed.configureTestingModule({ declarations: [MyModule], ...

What is the reason for a type narrowing check on a class property failing when it is assigned to an aliased variable?

Is there a way to restrict the type of property of a class in an aliased conditional expression? Short: I am trying to perform a type narrowing check within a class method, like this._end === null && this._head === null, but I need to assign the r ...

Using TypeScript to wrap a class with a Proxy object

I've been working on a function that takes an API interface (I've provided a sample here) and creates a Proxy around it. This allows me to intercept calls to the API's methods, enabling logging, custom error handling, etc. I'm running i ...

Utilizing ReactJS and TypeScript to retrieve a random value from an array

I have created a project similar to a "ToDo" list, but instead of tasks, it's a list of names. I can input a name and add it to the array, as well as delete each item. Now, I want to implement a button that randomly selects one of the names in the ar ...

Convert the date into a string format instead of a UTC string representation

I am currently working on a node.js project using TypeScript. In this project, I have a Slot class defined as follows: export class Slot { startTime: Date; constructor(_startTime: Date){ this.startTime = _startTime } } // Within a controller method ...