Tuesday, January 21, 2025

Get the Selected Value from Dropdown on Button Click in Angular

Requirement:

1. Get the Selected Value from Dropdown on Button Click in Angular

2. Disabled the dropdown once form submitted

3. Show Selected Value below after form Submitted

Solutions:

To achieve the functionality where dropdown fields are disabled, and their selected values are shown below after clicking the "Submit for Approval" button in Angular, you can implement it as follows:

Example Angular Code

HTML: Template file

<div *ngFor="let item of records">

  <label>{{ item.label }}</label>

  <select [(ngModel)]="item.selectedValue" [disabled]="isSubmitted">

    <option *ngFor="let option of item.options" [value]="option.value">

      {{ option.label }}

    </option>

  </select>

  <div *ngIf="isSubmitted">

    <p>Selected Value: {{ item.selectedValue }}</p>

  </div>

</div>

<button (click)="submitForApproval()">Submit for Approval</button>


TypeScript Code:

import { Component } from '@angular/core';

@Component({

  selector: 'app-records-management',

  templateUrl: './records-management.component.html',

  styleUrls: ['./records-management.component.css'],

})

export class RecordsManagementComponent {

  isSubmitted = false;

  records = [

    {

      label: 'Does your system store Records?',

      options: [

        { label: 'Yes', value: 'yes' },

        { label: 'No', value: 'no' },

      ],

      selectedValue: null,

    },

    {

      label:

        'Do you know angular?',

      options: [

        { label: 'Yes', value: 'yes' },

        { label: 'No', value: 'no' },

      ],

      selectedValue: null,

    },

  ];

  submitForApproval() {

    this.isSubmitted = true;

  }

}

Explanation

1. Dropdown Binding: The select element is bound to each item's selectedValue property using Angular's two-way binding ([(ngModel)]).

2. Disable Dropdown: When isSubmitted is true, the disabled property is applied to the dropdown.

3. Show Selected Value: After submission, the selected values are displayed below the dropdown using *ngIf="isSubmitted".

4. Submit Button: Clicking the "Submit for Approval" button sets isSubmitted to true, disabling the dropdowns and showing the selected values.

No comments:

Post a Comment