Sunday, October 31, 2021

Angular 12 select box binding to an object list

 In this sample the city field binds with CityList which is a list of objects consisting of id and names.

Required field validator is applied.



import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';

@Component({
  selector: 'app-mycomponent',
  templateUrl: './mycomponent.component.html',
  styleUrls: ['./mycomponent.component.css']
})
export class MycomponentComponent implements OnInit {

  CityList  = [
      {id : 1 , name : "Mumbai"},
      {id : 2 , name : "Pune"},
      {id : 3 , name : "Delhi"},
      {id : 4 , name : "Calcutta"}
    ];
  frm  = this.fb.group({
    firstName : ["" ,
      [Validators.required , Validators.minLength(3) , Validators.maxLength(6)]
    ],
    lastName : ["" ,[Validators.required]],
    city : ["" , [Validators.required]]
  });

  selectedCityId : number = 0;

  constructor(private fb : FormBuilder) { }

  ngOnInit(): void {
  }

  submit()
  {
    alert(
      this.frm.get('firstName')?.value + " " +
      this.frm.get('lastName')?.value + " " +
      this.selectedCityId
      );
  }

  onCityChange(event: any)
  {
    this.selectedCityId = event.target.value;
  }

}



<p>mycomponent works!</p>

<form [formGroup] = "frm" (ngSubmit)="submit()">
    <table>
        <tr>
            <td>
                <label>First Name</label>
            </td>
            <td>
                <input type="text" formControlName="firstName" />
            </td>
        </tr>

        <tr>
            <td>
                <label>Last Name</label>
            </td>
            <td>
                <input type="text" formControlName="lastName" />                
            </td>
        </tr>


        <tr>
            <td>
                <label>City</label>
            </td>
            <td>
                <select formControlName="city" (change)="onCityChange($event)">
                    <option value="">Choose your city</option>
                    <option *ngFor="let city of CityList" [value]="city.id">
                    {{city.name}}</option>
                </select>
            </td>
        </tr>

        <tr>
            <td colspan="2">
                <button type="submit"  [disabled] = "!frm.valid">Submit</button>
            </td>
        </tr>

    </table>
</form>







No comments:

Post a Comment

How to check local and global angular versions

 Use the command ng version (or ng v ) to find the version of Angular CLI in the current folder. Run it outside of the Angular project, to f...