Search code examples
htmlangularformsangular-reactive-forms

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


I want to send error feedback by doing submitted check in Angular form control. But the form.submitted property does not work, so I am getting an error message. Property 'submitted' comes from an index signature, so it must be accessed with ['submitted'].

html file

<form #clientRequestForm [formGroup]="clientRequestForm" (ngSubmit)="newClientRequest()">
<div class="mb-3">
  <label class="form-label" for="username"
    >Username</label
  >
  <input
    type="text"
    class="form-control"
    id="email"
    formControlName="username"
    placeholder="Enter username"
    [class.is-invalid]="clientRequestForm.submitted && clientRequestForm.get('username')?.invalid"
  />
  <div class="invalid-feedback">
    <div>Username is required</div>
    
  </div>
</div>

<div class="mb-3">
  <label class="form-label" for="password">Item Type</label>
  <select name="" formControlName="itemid" class="form-select" id="" [class.is-invalid]="clientRequestForm.submitted&& clientRequestForm.get('itemId')?.invalid">
    <option value="{{item.itemid}}" *ngFor="let item of clientItems">{{item.itemname}}</option>
  </select>
  <div class="invalid-feedback">
    <div>Item is required</div>
    
  </div>
</div>
<div class="mt-5">
    <button type="submit" class="btn btn-success btn-load w-100" type="submit" [disabled]="loading">
        <span class="d-flex align-items-center">
            <span class="flex-grow-1 me-2"> {{CheckingText}} </span>
            <span
            *ngIf="loading"
            class="spinner-border flex-shrink-0"
            role="status"
            >
            </span>
        </span>
    </button>
</div>
</form>

component form code

clientRequestForm= new FormGroup({
    username: new FormControl(null, Validators.required),
    itemid: new FormControl(null, Validators.required)
  }, {updateOn : 'submit'})

How can I fix this?


Solution

  • The submitted property does not exist in a Form Group object type (https://angular.io/api/forms/FormGroup).

    An alternative could be to create a flag that changes when the form loads.

    export class ClientRequestComponent implements OnInit {
          submitted: boolean = false;
          ...
    
          newClientRequest(){
             submitted = true;
             if (this.clientRequestForm.valid) {
                ....
             }
          }
    }