How to get the value of FormControl in Angular 

How to get the value of FormControl in Angular

In this post, I am going to share how to get the value of FormControl in Angular 2+. I will show you an example using a reactive form.

The implementation shown below would work with all the versions of Angular 5 and above (Angular 6, Angular 7, Angular 8, Angular 9, Angular 10, Angular 11, Angular 12, and Angular 13).

AppCompoent.html

Let us say on submit, we want to alert the value of formControl hotelId. In this form shown below, on clicking the Save it is going to trigger the saveAmenities().

<form [formGroup]="hotelAmenityForm" (submit)="saveAmenities()">

              <input type="number" formControlName="hotelId" value="{{selectedHotelId}}">
              
              <label for="amenities" class="form-label">Hotel Facilities/Amenties</label>
              <ng-multiselect-dropdown [placeholder]="'Select Room Amenties'" [settings]="dropdownSettings"
                [data]="dropdownList" formControlName="hotelAmenity">
              </ng-multiselect-dropdown>

              <div class="d-flex gap-3 mt-3">
                <button class="btn btn-primary" type="submit">Save</button>
              </div>

            </form>Code language: HTML, XML (xml)

AppComponent.ts

hotelAmenityForm: FormGroup;
ngOnInit(): void {
    this.hotelAmenityForm = this.formBuilder.group({
      hotelId: [''],
      hotelAmenity: ['']
    });

    this.dropdownList = [
      { item_id: 1, roomAmenity: 'Wi-Fi' },
      { item_id: 2, roomAmenity: 'Bar' },
      { item_id: 3, roomAmenity: 'Foreign Currency Exchange' },
      { item_id: 4, roomAmenity: 'Laundry' },
      { item_id: 5, roomAmenity: 'Conference Hall' },
      { item_id: 6, roomAmenity: 'Lift' },
      { item_id: 7, roomAmenity: 'Luggage Storage' },
      { item_id: 8, roomAmenity: 'Front Desk Service: 24 hours' },
      { item_id: 9, roomAmenity: 'Parking' },
      { item_id: 10, roomAmenity: 'Library' },
    ];

    this.dropdownSettings = {
      singleSelection: false,
      idField: 'item_id',
      textField: 'roomAmenity',
      selectAllText: 'Select All',
      unSelectAllText: 'UnSelect All',
      // itemsShowLimit: 3,
      allowSearchFilter: true
    };
  }

saveAmenities(){
    alert(JSON.stringify(this.hotelAmenityForm.get('hotelId').value))
    
    // Logic to save data here
  }Code language: JavaScript (javascript)

The magic wand to get the value of formControl demonstrated in the above implementation is the line:

<code>this.hotelAmenityForm.get('hotelId').value)</code>Code language: HTML, XML (xml)

Output

How to get the value of FormControl in Angular
How to get the value of FormControl in Angular 

Leave a Reply

Discover more from BHUTAN IO

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top