How to make required form validation using Angular and FormBuilder

Viewed 148

I've been coding in angular, this is my first time working with material and form groups, and for the life of me I can't figure out how to add required validators. I've been following there https://angular.io/guide/form-validation, and I also tried https://material.angular.io/components/input/overview, But neither of them are working. Here's my code for the html file:

<mat-form-field class="full-width">
     <mat-label>Alert</mat-label>
     <input matInput id="name" formcontrolname="alert" placeholder="Ex. Red" accept=".pdf" required>
     <div *ngIf="(alert.dirty || alert.touched)" class="alert alert-danger">
          <div *ngIf="alert.errors?.['required']">
               Name is required
          </div>
     </div>
</mat-form-field>

And heres the code for the component file:

export class ReportUploadFormComponent {
  uploadFileForm: FormGroup;
  constructor(
    private fb: FormBuilder,
  ) {
    this.uploadFileForm = this.fb.group({
      patientId: ['', [Validators.required]],
      type: ['', [Validators.required]],
      device: ['', [Validators.required]],
      fieldLine: ['', [Validators.required]],
      serviceLine: ['', [Validators.required]],
      alert: ['', [Validators.required]]
    })

  }

  @Output() reportUploadForm: EventEmitter<ReportUploadOutput> = new EventEmitter();

  public uploadFile() {

    const outputValue: ReportUploadOutput = this.uploadFileForm.value;

    this.reportUploadForm.emit(outputValue);
  }

  get alert() { return this.uploadFileForm.get('alert'); }
  get type() { return this.uploadFileForm.get('type'); }
  get patientId() { return this.uploadFileForm.get('patientId'); }
  get fieldLine() { return this.uploadFileForm.get('fieldLine'); }
  get device() { return this.uploadFileForm.get('device'); }
  get serviceLine() { return this.uploadFileForm.get('serviceLine'); }

But no matter what, the error is not showing up even when I try to submit the alert field as empty. What am I doing wrong?

I also looked at this issue but it didn't work either How to set a custom error message to a form in angular

1 Answers

You have a typo (?), formcontrolname="..." should be...

 formControlName="..."

Notice the capital C and N. Also just a sidenote, I like to use hasError for showing errors, so in this case I would do:

*ngIf="alert.hasError('required')"
Related