Sunday, October 31, 2021

Angular 12 select box with a simple string list binding


Most Basic angular select box which binds to a list of strings. It has a "Choose" option and a required validator applied.

 

<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">
                    <option value="">Choose your city</option>
                    <option *ngFor="let city of CityList" [ngValue]="city">{{city}}</option>
                </select>
            </td>
        </tr>

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

    </table>
</form>


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  = ["Mumbai" , "Pune" , "Delhi" , "Calcutta"]
  frm  = this.fb.group({
    firstName : ["" , [Validators.required , Validators.minLength(3) , Validators.maxLength(6)]],
    lastName : ["" ,[Validators.required]],
    city : ["" , [Validators.required]]
  });

  constructor(private fb : FormBuilder) { }

  ngOnInit(): void {
  }

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

}




Remember that in html, "value" attribute binds to a scalar value while "ngValue" attribute binds to an object.








No comments:

Post a Comment

 using Microsoft.AspNetCore.Mvc; using System.Xml.Linq; using System.Xml.XPath; //<table class="common-table medium js-table js-stre...