I tried to do reactive form validation in angular but I am getting an error. My goal is for the program to warn the user when the user leaves the required fields blank.
product-add-forms2.component.ts
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Product } from '../product';
@Component({
selector: 'app-product-add-forms2',
templateUrl: './product-add-forms2.component.html',
styleUrls: ['./product-add-forms2.component.css']
})
export class ProductAddForms2Component implements OnInit {
constructor(private formBuilder: FormBuilder) { }
productAddForm: FormGroup;
product: Product = new Product();
createProductAddForm() {
this.productAddForm = this.formBuilder.group({
name: ["", Validators.required],
description: ["", Validators.required],
imageUrl: ["", Validators.required],
price: ["", Validators.required],
categoryId: ["", Validators.required],
});
}
ngOnInit(): void {
this.createProductAddForm();
}
add() {
if (this.productAddForm.valid) {
this.product = Object.assign({}, this.productAddForm.value)
}
}
}
product-add-forms2.component.html
<h3>New Product - Reactive</h3>
<form [formGroup]="productAddForm" (ngSumbit)="add()" class="form-group">
<div>
<input type="text" id="name" name="name" formControlName="name" class="form-control" placeholder="Ürün Adı">
<div class="alert alert-danger"
*ngIf="productAddForm.get('name').hasError('required') && productAddForm.get('name').dirty">Product name is required
</div>
</div>
</form>
when i run its showing error in
<div class="alert alert-danger"
*ngIf="productAddForm.get('name').hasError('required') && productAddForm.get('name').dirty">Product name is required
</div>
the part i'm talking about (hasError) and (dirty)