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

Discussão em 'Angular' iniciado por Chaitanya Chitturi, Novembro 19, 2024.

  1. 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 { }

    Continue reading...

Compartilhe esta Página