143

These are my files. I am getting this error can someone help me.

Error: src/app/app.component.html:5:123 - error TS4111: Property 'fName' comes from an index signature, so it must be accessed with ['fName'].
        <input id="name" type="text" formControlName="fName" class="form-control" [ngClass]="{'is-invalid':submitted && f.fName.errors}"/>

component.html

    <form [formGroup]="surveyForm" (ngSubmit)="onSubmit()">
      <div>
        <label>Name:</label>
        <input id="name" type="text" formControlName="fName" class="form-control" [ngClass]="{'is-invalid':submitted && f.fName.errors}"/>
        <div *ngIf="submitted && f.fName.errors" class="form-control">first name is required</div>
      </div>
    </form>

component.ts


    import { Component, OnInit } from '@angular/core';
    import { FormControl, FormBuilder, FormGroup, Validators} from '@angular/forms';
    @Component({
    selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
      })
      export class AppComponent implements OnInit{
        surveyForm!: FormGroup;
        submitted= false;

     constructor(private  formBuilder: FormBuilder){}

     ngOnInit(){
     this.surveyForm = this.formBuilder.group({
       fName: ['',Validators.required]
      });
    }  
    //name = new FormControl('');
    get f() { return this.surveyForm.controls; }

     onSubmit() {
     this.submitted = true;

    // stop here if form is invalid
    if (this.surveyForm.invalid) {
        return;
    }

    // display form values on success
    alert('SUCCESS!! :-)\n\n' + JSON.stringify(this.surveyForm.value, null, 4));
    }

     onReset() {
    this.submitted = false;
    this.surveyForm.reset();
    }}

module.ts


    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { ReactiveFormsModule } from '@angular/forms';
    import { AppRoutingModule } from './app-routing.module';
    import { AppComponent } from './app.component';
    import { FormsModule } from '@angular/forms';
    //import { FormBuilder } from '@angular/forms';

    @NgModule({
     declarations: [
       AppComponent
     ],
    imports: [
     BrowserModule,
     AppRoutingModule,
     FormsModule,
     ReactiveFormsModule,
     //FormBuilder
     ],
    //declarations: [AppComponent],
      providers: [
     //FormBuilder
     ],
     bootstrap: [AppComponent]
     })
     export class AppModule { }
3
  • 8
    I'm guessing you are on Angular v13. It basically asking you to change f.fName.errors to f['fName'].errors. Commented Nov 25, 2021 at 6:29
  • That works thank you so much. Commented Nov 25, 2021 at 6:47
  • @AdithyaSreyaj Indeed. That was the help I have needed. Now: formModel['errors']['required']
    – cluster1
    Commented Dec 24, 2022 at 11:59

15 Answers 15

274

In my opinion, this is a completely unnecessary feature in TypeScript. To disable it, you need to change the file tsconfig.json:

"compilerOptions": {
// ...
  "noPropertyAccessFromIndexSignature": false,
// ...
}
5
  • Restarting the angular application then solved the problem Commented Nov 16, 2022 at 18:53
  • 9
    I'm getting really sick of Typescript trying to completely turn Javascript into a new, fully typed language. It's not. They need to make it far easier to find and turn off these features.
    – Tim Hardy
    Commented Jan 24, 2023 at 23:24
  • 2
    The Angular documentation examples suggest coding it like the OPs question. So its surprising to me that The default template for an Angular 16 project has this option as true. angular.io/guide/typed-forms Commented Jun 6, 2023 at 4:18
  • 1
    @Harlin Same question for having to put a ? after every single variable name that's not initialized, meaning every variable... backwards, should be mark the one that need initializers.
    – Dan Chase
    Commented Dec 5, 2023 at 17:18
  • I removed my comment. I must have been having an off day lol. But trying to make javascript a more static language seems to be piling crap on top of crap. Oops, I made a cranky comment again :-D
    – Harlin
    Commented Dec 5, 2023 at 17:41
118

Let's clarify what the issue is. We are talking about a template-driven form validation. You need to validate something, let's say to ensure that a field is required (call it firstName). Note that from Angular v13, it changed a bit from an old code like this:

<div *ngIf="firstName.errors?.required">First Name is required</div>

to this

<div *ngIf="firstName.errors?.['required']">First Name is required</div>

As a reminder, the '?' is to ensure that the errors object is not null.

More details are here: https://angular.io/guide/form-validation

5
  • thanks! I'm new in angular and things like this are frustrating stuff :snif:. In my case it was from <div *ngIf="password.errors.required">Password is required</div> to <div *ngIf="password.errors['required']">Password is required</div> (I have to remove the dot too)
    – Rodrigo
    Commented Dec 22, 2022 at 16:57
  • 2
    Please reverse the edit, because an extra dot is actually required for optional chaining. It's either errors?.['required'] or errors['required'].
    – Tortila
    Commented Jan 16, 2023 at 18:14
  • 1
    It needs . after the question mark firstName.errors?.['required'] Commented Jan 26, 2023 at 8:10
  • 1
    Any idea why angular has changed from errors?.required to errors?.['required']? Commented Apr 24, 2023 at 5:42
  • 3
    @RakeshSojitra ValidationErrors has index signature, and in TS 4.2 noPropertyAccessFromIndexSignature flag was released.
    – Tortila
    Commented Jul 31, 2023 at 22:28
19

Change this key value to false in tsconfig.json file

"noPropertyAccessFromIndexSignature": false

0
12

add the following line to tsconfig.json file, or set it to false if already exist

"noPropertyAccessFromIndexSignature": false,
3
  • This is a good answer. :) Solves the problem without making the sourcecode more verbose. Typescript is a little bit overrated. Commented Dec 13, 2023 at 10:59
  • Really, this is great answer. Saved lot of times.
    – Arun Singh
    Commented Apr 18 at 12:16
  • This should be the Accepted Answer. Thanks bro
    – Tal Kohavy
    Commented Jul 27 at 7:18
10

Angular 13 Form Validation with Reactive Forms Example

add form() getter for easy access to form fields in *.component.ts file

//convenience getter for easy access to form fields
get form(): { [key: string]: AbstractControl; }
{
    return this.signInForm.controls;
}

Access to email field errors example

form['email'].errors

form['email'].errors['required']

form['email'].errors['email']

signInForm HTML example

<form [formGroup]="signInForm" (ngSubmit)="onSubmit()">

    <div class="form-group">
        <label for="email">Email</label>
        <input type="email" formControlName="email" class="form-control"
            [ngClass]="{ 'is-invalid': submitted && form['email'].errors }" />
        <div *ngIf="submitted && form['email'].errors" class="invalid-feedback">
            <div *ngIf="form['email'].errors['required']">
                Field is required
            </div>
            <div *ngIf="form['email'].errors['email']">
                Email format is invalid
            </div>
        </div>
    </div>

    <div class="form-group mt-3">
        <label for="password">Password</label>
        <input type="password" formControlName="password" class="form-control"
            [ngClass]="{ 'is-invalid': submitted && form['password'].errors }" />
        <div *ngIf="submitted && form['password'].errors" class="invalid-feedback">
            <div *ngIf="form['password'].errors['required']">
                Password is required
            </div>
        </div>
    </div>

    <div class="mt-3 d-flex justify-content-between">
        <button type="submit" [disabled]="isLoading" mat-flat-button color="primary">
            <span *ngIf="isLoading" class="spinner-border spinner-border-sm mr-1"></span>
            Sign in
        </button>
    </div>

</form>
8

In angular 14.0.4, it only worked for me with

<div *ngIf="user?.errors?.['required'] ">First Name is required</div>
1
  • I bet the first question mark is unnecessary. user.errors?.['required'] would also work fine! Commented Jun 7, 2023 at 8:14
4

Answer:

<span *ngIf="username?.errors?.['required']">Name is required</span>
<span *ngIf="username?.errors?.['minlength']">
    Name must be 3 
charchters</span>

Here is the answer to the question Error: src/app/reactive-signup/reactive-signup.component.html:16:52 - error TS4111: Property 'required' comes from an index signature, so it must be accessed with ['required'].

<span *ngIf="username?.errors.required">
    Name is required
</span>
2

Please use f['fName'].errors instead of f.fName.errors.

<input id="name" type="text" formControlName="fName" class="form-control" [ngClass]="{'is-invalid':submitted && f['fName'].errors}"/>
1

try this one it should work fine

<div *ngIf="shippingAddressZipCode?.invalid && (shippingAddressZipCode?.dirty || shippingAddressZipCode?.touched)" class="alert alert-danger mt-1">
                  <div *ngIf="shippingAddressZipCode?.hasError('required') || shippingAddressZipCode?.hasError('notOnlyWhiteSpace')">Zip Code is required.</div>
                  <div *ngIf="shippingAddressZipCode?.hasError('minlength')">Zip Code should be at least 5 Digit.</div>
                </div>
0

Angular 13 Form Validation with Reactive Forms and Form Builder, I had found the solution in Angular document, they have some different with Angular 12, you can try this:

<div *ngIf="submitted && surveyForm.get('fName')?.valid" class="form-control">first name is required</div>
0

worked in my case.

<div *ngIf="firstName.errors?.required">
        <b>First Name is required</b>
      </div>
2
  • As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
    – Community Bot
    Commented Apr 13, 2022 at 1:04
  • It worked in your case because you have "noPropertyAccessFromIndexSignature": false, so please do remove your answer since it isn't useful Commented Aug 29, 2022 at 15:27
0

Check on this example

file.ts

formBuilderInit() {
        this.form = this.formBuilder.group({
            first_name: [null, Validators.required],
            middle_name: [],
            last_name: [null, Validators.required],
            email: [],
            tel: [null, [Validators.required, Validators.pattern('^[0-9]{12}$')]],
        });
    }

    // convenience getter for easy access to form fields
    get f(): { [key: string]: AbstractControl; } {
        return this.form.controls;
    }

file.html

<mat-label for="tel">Telephone</mat-label>
    <mat-form-field>
       <input
          type="number"
          matInput
          formControlName="tel"
          class="form-control"
          placeholder="Ex: 250722353933"
          [ngClass]="{ 'is-invalid': submitted && f['tel'].errors }"
       />
       </mat-form-field>
       <div *ngIf="submitted && f['tel'].errors" class="invalid-feedback">
        <div *ngIf="f['tel'].errors['required']">Telephone Number is required</div>
            <div *ngIf="f['tel'].errors['pattern']">
               Phone number must be at least 12 digit numbers
            </div>
       </div>
0

Dont forget insert dot (.) between erros? and ['required'] like below

<div *ngIf="firstName.errors?.['required']">First Name is required</div>

For mores informations (angular 15) goes this link: https://angular.io/guide/form-validation

1
  • You could copy paste an example from the docs in order to help the viewer pinpoint the exact location. Just mentioning it as a possible improvment in your answer.
    – jimas13
    Commented Jan 17, 2023 at 21:19
0

Angular form validation with error property of ngmodel in newer version of angular include following tag has required attribute validation *<div ngIf="phone.hasError('required')">phone number is required this pattern ('required') helped me in resolving the error

-2

Bro just use f['fullName'].errors[required] instead of f.fName.errors.required

Q:Property 'fullname' comes from an index signature, so it must be accessed with ['fullname']

1
  • As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
    – Community Bot
    Commented Sep 27, 2022 at 20:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.