The property 'name' is not found within the type 'FormGroup'

I am encountering an issue with form validation in my Angular app using ReactiveForms. The error message reads as follows:

Error:

src/app/pages/contact/contact.component.ts(48,32): error TS2339: Property 'assunto' does not exist on type 'FormGroup'. src/app/pages/contact/contact.component.ts(50,57): error TS2339: Property 'assunto' does not exist on type 'FormGroup'. src/app/pages/contact/contact.component.ts(51,30): error TS2339: Property 'nome' does not exist on type 'FormGroup'. src/app/pages/contact/contact.component.ts(52,33): error TS2339: Property 'empresa' does not exist on type 'FormGroup'. src/app/pages/contact/contact.component.ts(53,32): error TS2339: Property 'email' does not exist on type 'FormGroup'. src/app/pages/contact/contact.component.ts(54,34): error TS2339: Property 'telefone' does not exist on type 'FormGroup'.

Contact Component HTML

<form class="col-s4 dados-form" [formGroup]="dadosForm">

<mat-form-field style="width:100%" class="full-width">
  <input matInput placeholder="Name" formControlName="nome" required>
  <mat-error *ngIf="dadosForm.get('nome').dirty || dadosForm.get('nome').touched">
    Please fill in the name field</mat-error>
</mat-form-field> <br>

<mat-form-field style="width:100%" class="full-width">
  <input matInput placeholder="Company" formControlName="empresa" required>
  <mat-error
    *ngIf="dadosForm.get('empresa').dirty || dadosForm.get('empresa').touched">
    Please fill in the company field</mat-error>
</mat-form-field> <br>

<mat-form-field style="width:100%" class="full-width">
  <input matInput placeholder="E-Mail" formControlName="email" required>
  <mat-error
    *ngIf="dadosForm.get('email').dirty || dadosForm.get('email').touched">
    {{getMailErrorMessage()}}</mat-error>
</mat-form-field> <br>
<mat-form-field style="width:100%" class="full-width">
  <input matInput maxlength="15" id="phoneInput" formControlName="telefone" [mask]="phoneMask" placeholder="Contact Number" required />
  <mat-error
    *ngIf="dadosForm.get('telefone').dirty || dadosForm.get('telefone').touched">
    Please fill in the phone number field</mat-error>
</mat-form-field> <br>

<mat-form-field style="width:100%" class="full-width">
  <mat-label>Desired Product</mat-label>
  <mat-select matInput formControlName="assunto" required>
    <mat-optgroup *ngFor="let category of products" [label]="category.key">
      <mat-option *ngFor="let product of category.value" [value]="product">
        {{product}}
      </mat-option>
    </mat-optgroup>
  </mat-select>
  <mat-error
    *ngIf="dadosForm.get('assunto').dirty || dadosForm.get('assunto').touched">
    Please select a desired product</mat-error>
</mat-form-field><br>

<mat-form-field style="width:100%" class="full-width">
  <textarea matInput placeholder="Message" formControlName="mensagem" required></textarea>
  <mat-error
    *ngIf="dadosForm.get('mensagem').dirty || dadosForm.get('mensagem').touched">
    Please fill in the message field</mat-error>
</mat-form-field><br>

<div class="form-buttons">
  <button mat-button mat-raised-button id="submitButton" [disabled]="!dadosForm.valid" matTooltip="" color="primary" (click)="sendMail(message)">Send</button>
</div>

</form>

Contact Component Typescript

  dataForm = new FormGroup({
    nome: new FormControl('', [Validators.required]),
    empresa: new FormControl('', [Validators.required]),
    email: new FormControl('', [Validators.required, Validators.email]),
    telefone: new FormControl('', [Validators.required]),
    assunto: new FormControl('', [Validators.required]),
    mensagem: new FormControl('', [Validators.required])
  });

Answer №1

<div *ngIf="f.name.invalid && f.name.touched">
                                <small class="text-danger" *ngIf="f.name.errors?.required">Please enter the name!</small>
                            </div>

This is the code snippet from the TypeScript file:

get f() { return this.form.controls; }

Answer №2

When encountering that error, I made a small adjustment in the first input as an example:

<mat-error *ngIf="dadosForm.get('nome').dirty || dadosForm.get('nome').touched">O campo nome deve ser preenchido</mat-error>

To simplify the validation within the *ngIf, you can make the following change:

<mat-error *ngIf="dadosForm.get('nome').invalid && (dadosForm.get('nome').dirty || dadosForm.get('nome').touched)">O campo nome deve ser preenchido</mat-error>

In my Angular 10+ project using the same input template, I avoid using dirty and touched. Instead, for a unique validation, I rely on dadosForm.invalid within the *ngIf to display the specific error message being validated.

An alternative approach would be:

<mat-error *ngIf="dadosForm.get('nome').invalid">O campo nome deve ser preenchido</mat-error>

Or even simpler:

<mat-error *ngIf="dadosForm.invalid">O campo nome deve ser preenchido</mat-error>

Answer №3

Utilize the form builder FormBuilder para validações

Primeiro importe essas dependências

import { FormGroup, FormBuilder, Validators } from '@angular/forms';

Crie uma variável para o grupo de formulários

formGroupName: FormGroup;

constructor(private _formBuilder: FormBuilder) { }

Defina o código de validações no método ngOnInit

this.formGroupName = this._formBuilder.group({
    nome: ['', Validators.required],
    empresa: ['', Validators.required],
    email: ['', [Validators.required, Validators.email]],
    telefone: ['', Validators.required],
    assunto: ['', Validators.required],
    mensagem: ['', Validators.required]
});

Tente com isso.

Answer №4

If you happen to encounter this particular error while working on a similar task as mine, the following information might be of assistance. I received the error message:

"Property 'group' does not exist on type 'FormGroup'.ts(2339)"

this.searchForm = this.fb.group({
  clientName: ['', [noWhitespaceValidator]],
  startDate: [''],
  endDate: [''],
})

The reason behind this error was that I had initialized the form without importing the formBuilder. Consequently, without injecting it as a constructor dependency, the error occurred because 'group' could not be found in fb.group.

I share this in hopes that it may be beneficial to someone facing a similar issue.

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

Is there a way to verify if the $compile process has finished?

I am currently developing a function that can dynamically create an email template from an HTML template and some provided data. To accomplish this, I am utilizing Angular's $compile function. However, I have encountered a challenge that I seem unabl ...

How can I customize the visibility toggles for the password input field in Angular Material?

Currently immersed in the Angular 15 migration process... Today, I encountered an issue with a password input that displays two eyes the first time something is entered in the field. The HTML code for this is as follows: <mat-form-field appearance=&qu ...

The Route.ts file does not export any HTTP methods

Encountering an error while trying to migrate code from Next JS 12 with pages router in Javascript to Next JS 13 with TypeScript. ⨯ Detected default export in 'vibe\src\app\api\auth[...nextauth]\route.ts'. Export a name ...

Contrasting Dependency Injection with Exporting Class Instances

I've been diving into the world of TypeScript and working on enhancing my skills as a web developer. One project I'm currently focused on is a simple ToDo app, which you can find here: https://github.com/ludersGabriel/toDo/tree/dev/backend. My q ...

How can I properly send a file to express-fileupload using a post request in Angular 9?

I have successfully accomplished this task in Postman by following this link: https://i.sstatic.net/dKs8b.png However, when attempting to do the same in Angular, the functionality does not seem to be working. Below is the Angular code snippet: <input ...

Issue in TypeScript where object properties may still be considered undefined even after verifying using Object.values() for undefined values

I'm encountering an issue with TypeScript regarding my interface MentionItem. Both the id and value properties are supposed to be strings, but TypeScript is flagging them as possibly string | undefined. Interestingly, manually checking that id and va ...

Troubleshooting: Issue with Angular integration causing foreign key lookup failure in ABP Framework

ABP version: 5.3.3 Frontend: Angular I'm attempting to implement the same process outlined here in order to create a lookup dropdown for an additional property named Bank Id, but it's not functioning as expected. private static void ConfigureExt ...

The specified property is not found in the type 'IntrinsicAttributes & IntrinsicClassAttributes<DatePicker> & Readonly<{ children?: ReactNode; }>'

As I delve into utilizing React along with TypeScript and Material-UI components, I encounter some errors. One such error message pops up like this: The Property 'openToYearSelection' is not found on type 'IntrinsicAttributes & Intr ...

What is the best way to distinguish between administrators and regular users in an Angular project?

I am embarking on a project using Angular and I plan to incorporate both an admin and a user section within it. Is there a way to effectively separate the admin area from the user area in Angular? Additionally, how can I differentiate the style files for ...

constructor parameters not being flagged as unused by no-unused-vars plugin

I have a variable in the constructor that is not being used, and only tsc seems to pick up on it. Even though I have tried various plugins and recommendations to get eslint to recognize the unused variable, it still doesn't work. I have experimented ...

custom field component for react-hook-form

I have been working on creating a form field component that can be utilized at both the root form level and as a nested field. export type FirstNameField = { firstName: string; }; type GenericFormType<T, NS extends string | never = never> = NS ext ...

The field 'password' is not found in the 'User' array type

I'm encountering an issue with my Typescript code: Property 'password' does not exist on type 'User[]'.ts(2339). Do I need to create an interface or something similar? Thank you in advance. usersRouter.post("/", async ...

What is the best way to populate an Angular Bootstrap Table Widget with data obtained from an API request?

I am currently in the process of making an API call and utilizing the received data in a Bootstrap Angular Table Widget. The specific widget I am utilizing can be found here: Complete example (Angular powered bootstrap widget) Ensure you are working with ...

What is the best way to retrieve unique column values using the LoopBack REST API?

I am working with a loopback REST API that fetches data from a MySQL table and returns it in JSON format. However, I need to apply a filter or query so that only distinct values for a specific column are returned. In SQL, we use the syntax SELECT DISTINC ...

Implementing a Name Interface in Typescript - A Step-by-Step Guide

export declare const TerminalWidgetOptions; unique symbol; export interface TerminalWidgetOptions { endpoint: Endpoint.Options, id: string, caption: string, label: string destroyTermOnClose: boolean } Upon implementing this interface i ...

The Angular Material Autocomplete component fails to show items upon upgrading the angular/material package to the newest version

Issue with Angular Material Autocomplete component not displaying items after updating angular/material package to the latest version. The autocomplete was functioning correctly with "@angular/material": "^2.0.0-beta.10" but encountered issues when update ...

Ways to retrieve form information from a POST request

I received a POST request from my payment gateway with the following form data: Upon trying to fetch the data using the code snippet below, I encountered errors and gibberish content: this.http .post<any>('https://xyz.app/test', { ti ...

Can you provide guidance on how to extract the ID from a Firebase reference in the "onCreate" or "onUpdate" triggers?

I have a scenario where I need to fetch specific values under {id} in the .onUpdate() method. Var3 is a nested object, while var2 is a single variable. Is there a way to extract {id} from onUpdate and pass it as an argument to customMethod so that I can ut ...

Change the object's data type while preserving the connection between keys and values

Imagine having a defined object type, for example: interface A { foo: string; bar: number; baz: boolean; // … } Is there a way to use a generic type to completely change its structure while maintaining the key-value relationship? One possibilit ...

Utilizing the component within the template could potentially result in a cyclical dependency if it were to be imported

I have encountered an issue with two components that reference each other in a recursive manner. Ever since I upgraded to Angular 13, I am unable to use it and I keep receiving the error mentioned in the title. Component A (field.component.html): <app- ...