Combine the selected values of two dropdowns and display the result in an input field using Angular

I am working on a component that consists of 2 dropdowns. Below is the HTML code snippet for this component:

<div class="form-group">
      <label>{{l("RoomType")}}</label>
     <p-dropdown [disabled] = "!roomTypes.length"  [options]="roomTypes" autoWidth="false"  [style]="{'width':'100%'}" name="roomTypes" [autoWidth]="true" [(ngModel)]="room.roomTypeId"></p-dropdown>
</div>

<div class="form-group">
        <label>{{l("RoomNumber")}}</label>
        <p-dropdown [disabled] = "!roomNumbers.length"  [options]="roomNumbers" autoWidth="false"  [style]="{'width':'100%'}" name="numberRoom" [autoWidth]="true" [(ngModel)]="room.roomNumber"></p-dropdown>
</div>  

The population of these dropdowns in typescript is as follows:

getRoomTypes(): void {
    this._roomTypeService.getRoomTypesDropdownValues().subscribe(r => {
        r.items.forEach((value) => {
            this.roomTypes.push({label: value.name, value: value.id});
        });
    });
}

getRoomNumber(): void {
    for (let i = 1; i <= 10; i++) {
        this.roomNumbers.push({label: i.toString(), value: i});
    }
}

After the dropdowns, I have an input field that needs to display the concatenated label of the selected options from both dropdowns.

Here is the input field:

<div class="form-group"> 
                    <label>{{l("RoomName")}}</label>
                    <input #roomNameInput="ngModel" class="form-control" type="text" name="roomName" [(ngModel)]="room.roomName"   maxlength="32">
                </div>

I attempted to achieve this by using

(ngModelChange)="setRoomName(room.roomTypeId,room.roomNumber)"
on both dropdowns, but it only returned the id values.

Can anyone guide me on how to correctly concatenate the labels from the dropdown options?

Answer №1

My recommendation is to implement a reactive form as it offers a cleaner and more understandable approach. By using a reactive form, your code will look something like this:

In the template:

<form [formGroup]="roomForm">
  <select class="form-control" formControlName="roomType">
    <option *ngFor="let opt of types" [ngValue]="opt">{{ opt.label }}</option>
  </select>
  <select class="form-control" formControlName="roomNumber">
    <option *ngFor="let opt of nums" [ngValue]="opt">{{ opt.label }}</option>
  </select>
  <input class="form-control" formControlName="inputString"/>
</form>

And in the component:

export class Component   implements OnInit {
  nums  = [{label: 'label 1', value: 1 }, {label: 'label 2', value: 2}, {label: 'label 3', value: 3}];
  types = [{label: 'label a', value: 'a'}, {label: 'label b', value: 'b'}, {label: 'label c', value:'c'}];
  inputNum: string = '';
  inputType: string = '';
  subs: Subscription[] = [];

  roomForm: FormGroup;

  ngOnInit() {
    this.roomForm = new FormGroup({
      roomType: new FormControl(),
      roomNumber: new FormControl(),
      inputString: new FormControl()
    })
    this.subs.push(
      this.roomForm.get('roomType').valueChanges.subscribe((val) => {
        this.inputType = val.label;
        this.roomForm.get('inputString').setValue(this.inputNum + this.inputType);
      })
    )

    this.subs.push(
      this.roomForm.get('roomNumber').valueChanges.subscribe((val) => {
        this.inputNum = val.label;
        this.roomForm.get('inputString').setValue(this.inputNum.toString() + this.inputType);
      })
    )
  }
}

To utilize reactive forms, make sure to import ReactiveFormsModule in your module. I hope this helps in resolving your issue!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to prevent a specific class from using CSS styling

My HTML <body> <div id="finalparent"> <!--many parent divs here--> <div id="1stparent"> <div id="txt_blog_editor" class="box" style="width: 1097px;"> <div class="abc anotherclass"> </div> & ...

What is the best way to showcase two SVG clocks on a single webpage?

The issue arises when combining the desktop and mobile versions of the clock script. The first clock works fine on its own, but upon duplicating another set of scripts for the second clock, it encounters display problems. I have appropriately labeled the c ...

Error message: Injector Error: R3InjectorError(Standalone[_AppComponent])[_WebService -> _WebService -> _WebService] occurred

Being a student, I must apologize in advance for any mistakes in terminology or gaps in my understanding. I am currently developing an Angular front-end to communicate with my backend API. However, I keep encountering the following error in the web page c ...

Using ES6 Classes to map an array of variables

If I have a list of 5 people's names, such as Sam, Ash, Moe, Billy, Kenzi, and want each name to have properties like doneHomework and lazy using a class: class Person { constructor() { this.doneHomeWork = 0; this.lazy = false; ...

Tips for concealing the bar graph while maintaining the visibility of the data labels in HighCharts

Is there a way to hide one bar but keep the data labels in HighCharts? I have 3 bars: Target Realization Percentage I want to display only the first and second bars, with only 1 data label which is the percentage. So, I made some adjustments to my co ...

positioning a window.confirm dialog box in the center of the screen

I'm currently facing an issue with a dialog box that I have implemented successfully. However, I can't seem to get it centered on the page: <Button variant="danger" onClick={() => { if (window.confirm('Delete character?')) handle ...

Tips for managing this JavaScript JSON array

Here is an example of a JSON array: var data = { name: 'Mike', level: 1, children: [ { name: 'Susan', level: 2, }, { name: 'Jake', level: 2 }, { name: 'Roy', level: 2 }, ...

Avoiding memory leaks when using three.js with a large number of shapes

My code is devouring memory at an alarming rate and ultimately crashing. After some investigation, I've determined that the issue seems to be related to the torus generation/removal portion of the code. Despite efforts to manage the scene array and t ...

The process of generating an efficient build gets stuck and never finishes

I am currently facing an issue while attempting to build my React app. Whenever I execute "npm run build," the terminal gets stuck at "Creating and optimized production build..." and doesn't complete the process. I have tried running this on a system ...

Themeing for dark mode using styled components in Next JS

I have been searching for an answer to this question, but haven't found one yet Currently, I am using styled components with next js along with the use-dark-mode hook to manage theme changes and detection The global styles switch seems to work fine ...

What could be causing my form not to Submit when attempting submission without utilizing the submit button?

Here is the code for my validation: $(function () { function validateForm() { // Code to validate form inputs } $('#myform').submit(validateForm); }); After this, I want to submit the form when a certain action occurs: < ...

How to extract a particular value from a JSON object using AJAX?

In my test.php file, I have implemented a code where ajax sends a request from index.php to this page. Within this page, I have created an array, converted it to JSON, and returned it as follows: <?php $arr = array( "status"=>200, "result"=>array ...

Is Nextjs the best choice for developing the frontend code exclusively?

When deciding whether to use Next.js or plain React for my front-end development, should I consider that a back-end already exists? If I am not planning to write a new back-end, which option would be better suited for the project? ...

Attempting to create a dynamic dropdown menu with animated effects triggered by a key press

I've been attempting to construct a menu that initially appears as a small icon in the corner. Upon pressing a key (currently set to click), the checkbox is activated, initiating the animation. Most of the menu and animation are functional at this po ...

What is the process for establishing a key on the request header to authenticate in Node.js?

I am a novice in the world of nodejs. My current project involves creating a basic server that writes JSON data to a CSV file. However, I have encountered a stumbling block: For authentication purposes, the request header must include an “appKey” para ...

Angular app - static List mysteriously clears out upon refresh

My goal is to create a login page using Angular. I have an Angular component with HTML, CSS, and TypeScript files that manage this functionality. The HTML file contains two fields (Username and Password) and two buttons (Login and Register). When a user en ...

Using JQuery's ajax() method within a for loop

I'm currently working on implementing default edit mode in a Razor view. Everything seems to be functioning properly except for the filling function for the dropdown list. As part of my task, I need to populate the state dropdown list based on the cur ...

Transfer an URL parameter from the URL to the server using PHP or JavaScript

My goal here is to pass the URL as a parameter named "web_url". The code snippet above shows an AJAX request being sent to a PHP server on the backend. On the PHP side, I'm attempting to capture this parameter using: $web_url = $_GET["web_url"]; H ...

Maintaining personalized variable values for individual connected clients in Node.js: What's the best approach?

I have recently started working with Node.js and I am using Visual Studio 2015 with the Basic Node.js Express 4 app template. After setting some values through a post request from the client, I noticed that when I open another tab and send another post re ...

Client-side filtering of jqGrid with multiple conditions

I am faced with a challenge in filtering records in a jqGrid based on multiple conditions. For example, if there are columns for Name, Age, and City, and I need to filter the grid using the following condition: Name = "Mark" and Age = 25 and City = &apos ...