2

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 Answer 1

0

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')"
Sign up to request clarification or add additional context in comments.

1 Comment

Well now I feel like an idiot. Thanks! This works great, and I tried the has error as well

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.