Kaan Taha Köken
Kaan Taha Köken

Reputation: 963

Form validation with mat-error on Angular

I have just started to learn angular with some youtube videos. I was learning the form validation, and the video I have followed used these type of conventions:

<mat-error *ngIf="content.invalid">Sth as Error</mat-error>
<mat-error *ngIf="postForm.getControl('title').invalid">Sth as Error</mat-error>

Moreover, I tried myself, but apparently, it did not work. What are the reasons that they do not work? Is it an old convention?

Full Code:

post-create.component.html

<mat-card>
  <form (submit)="onAddPost(postForm)" #postForm="ngForm">
    <mat-form-field>
      <input
        matInput
        type="text"
        name="title"
        ngModel
        required>
      <mat-error *ngIf="postForm.getControl('title').invalid">Enter Smt</mat-error>
   </mat-form-field>
   <mat-form-field>
      <textarea
         matInput
         rows="4"
         name="content"
         ngModel
         required
         #content="ngModel">
      </textarea>
      <mat-error *ngIf="content.invalid">Enter stm</mat-error>
   </mat-form-field>
   <button
      mat-raised-button
      color="primary"
      type="submit">Save Post</button>
 </form>
</mat-card>

post-create.component.ts

import { Component, EventEmitter, Output } from '@angular/core';
import { Post } from '../post.model';
import { NgForm } from '@angular/forms';

@Component({
   selector: 'app-post-create',
   templateUrl: './post-create.component.html',
   styleUrls: ['./post-create.component.css']
})

export class PostCreateComponent {
    @Output() postCreated = new EventEmitter<Post>();

    onAddPost(form: NgForm) {
      if (form.invalid) {
         return;
      }

      const post: Post = {
         title: form.value.title,
         content: form.value.content
      };
      this.postCreated.emit(post);
    }
}

UPDATE: I found that this one is the broken one

<mat-error *ngIf="postForm.getControl('title').invalid">Sth as Error</mat-error> How can I fix it in the same way (without adding reference)?

Upvotes: 1

Views: 8896

Answers (1)

Kaan Taha K&#246;ken
Kaan Taha K&#246;ken

Reputation: 963

I found the answer. The reason is getControl(). It does not work. My friend explained to me that getControl() expects a FormControl instance, not a string. Therefore, I could add a reference and I could use like

<mat-error *ngIf="postForm.getControl(title)?.invalid">...</mat-error> (title added as a local reference)

OR I could use it like without reference

<mat-error *ngIf="postForm.form.get('title')?.invalid">...</mat-error>

Upvotes: 3

Related Questions