Home > Software engineering >  how to show default value in angular forms with validation?
how to show default value in angular forms with validation?

Time:07-15

I am having some difficulty with this form.

I am trying to make a form which can validate and also display a default value at the start. The problems I am facing:

  1. Once I add in the line "formControlName"=price, "formControlName"=description, "formControlName"=name, the value is no longer displayed on the screen.

Before adding the line "formControlName" Values can appear

After adding the line "form ControlName" Has Validation, but even after form is valid cannot get alert

  1. Cannot validate form properly, when I remove the value I set in the html file, and enter a new value. The form does not trigger an alert dialogue as expected.

Code (HTML)

<div >
  <h2>Edit Product Details</h2>


  <form [formGroup]="updateProductForm" (ngSubmit)="submit()">
    <label for="pname">Product Name:</label><br>
    <input type="text" id="pname" name="pname" value={{products.name}}><br>
    <!-- error lies here -->
    <div  *ngIf="fc.pname.errors && isSubmitted">
      <div *ngIf="fc.pname.errors.required">Should not be empty</div>


    </div>
    <label for="price">Unit Price:</label><br>
    <input type="text" id="price" name="price" value={{products.price}}><br>
    <!-- error lies here -->
    <div  *ngIf="fc.price.errors && isSubmitted">
      <div *ngIf="fc.price.errors.required">Should not be empty</div>


    </div>

    <label for="price">Product Description:</label><br>
    <textarea type="text" style="overflow: scroll; height: 200px; width: 500px;" value={{products.description}}
      id="description" name="description"> </textarea><br>
    <div  *ngIf="fc.description.errors && isSubmitted">
      <div *ngIf="fc.description.errors.required">Should not be empty</div>


    </div>
    <label for="img">Change Display Image:</label><br>
    <input type="file" id="img" name="img" accept="image/*"><br><br>
    <button type="submit">Update Product Details</button>
    <button style="margin-left: 10px;">Delete Product</button>
  </form>
</div>

Code(type-script)

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { CartService } from '../cart.service';
import { FavService } from '../fav.service';
import { products } from '../models/products';
import { ProductsService } from '../products.service';

@Component({
  selector: 'app-update-delete-product',
  templateUrl: './update-delete-product.component.html',
  styleUrls: ['./update-delete-product.component.css']
})
export class UpdateDeleteProductComponent implements OnInit {
  updateProductForm!: FormGroup;
  isSubmitted = false;
  products!: products;
  constructor(private activatedRoute: ActivatedRoute, private productService: ProductsService,
    private cartService: CartService, private router: Router, private formbuilder: FormBuilder) {
    activatedRoute.params.subscribe((params) => {
      if (params.id)
        this.products = productService.getProductsById(params.id)
    }
    )
  }

  ngOnInit(): void {
    this.updateProductForm = this.formbuilder.group({
      pname: ['', [Validators.required]],
      price: ['', Validators.required],
      description: ['', Validators.required]

    });
  }
  get fc() {
    return this.updateProductForm.controls;
  }
  submit() {
    this.isSubmitted = true;
    if (this.updateProductForm.valid) return alert(`You have succefully updated the form!`)
    // alert (`email: ${this.fc.email.value},
    // password: ${this.fc.password.value}`)
  }

}

CodePudding user response:

Answer

  1. Once I add in the line "formControlName"=price, "formControlName"=description, "formControlName"=name, the value is no longer displayed on the screen.

Instead of this

<input type="text" id="pname" name="pname" value={{products.name}}>

do this as I wrote for all inputs with the correct name

<input type="text" id="pname" formControlName="pname">

Should work properly

  1. Cannot validate form properly, when I remove the value I set in the html file, and enter a new value. The form does not trigger an alert dialogue as expected.

This is due to the fact that, because you did not associate each input to the correct control with the formControlName property, form cannot find the data it expects and because of that it does not perform validation

After fixing the first point, validation should also work fine

See the official documentation for more informations, it is very clear and helpful


Additional Tips

To set the default values in the various controls, instead of doing this

<input type="text" id="pname" formControlName="pname" value={{products.name}}>

remove value property and do this

 this.formbuilder.group({
  pname: [products.name, Validators.required], // first parameter represents the default value
  price: [products.price, Validators.required],
  description: [products.description, Validators.required],
});

in your case, you retrieve the product data in the constructor() via the productService so when onInit() is called you should already have the data in products

For more information about that, look this StackOverflow answer


I hope I was helpful, let me know how it goes! :)

  • Related