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

Issues arise when trying to manage HTML received as a response from a server in plain text

I have a scenario where I am dynamically generating an HTML table on the server side using Java and then sending it to the client as JSON data. The response looks something like this: <table class="table"></table><thead class="thead-dark"&g ...

Reveal/Conceal footer upon vertical scrolling

I am attempting to achieve the following goals: Display the div element when the scrolling position is greater than 20 Apply a fadeOut effect after a certain delay Prevent the fadeOut effect when hovering over the sticky footer This is my implementation ...

Angular Recursive Bootstrap Breadcrumb Guide

I am looking to implement the bootstrap breadcrumb component (https://getbootstrap.com/docs/4.0/components/breadcrumb/) in my project. My goal is to use the breadcrumb to show the entire path to the current directory within a component that resembles a di ...

Leveraging Angular2's observable stream in combination with *ngFor

Below is the code snippet I am working with: objs = [] getObjs() { let counter = 0 this.myService.getObjs() .map((obj) => { counter = counter > 5 ? 0 : counter; obj.col = counter; counter++; return view ...

Using the Grails asset-pipeline with an external JavaScript library

In transitioning from Grails 2 to Grails 3, I am facing the challenge of managing my JavaScript files with the asset-pipeline plugin. The issue lies in using external libraries such as globalize and ajax-solr, which are large and consist of multiple interd ...

What is the method for including a placeholder with sequential numbering?

When I click on the "Add String" button, it clones the first table row with an input in the table and adds it to the table. I also need to add a +1 number in the placeholder of the copied element. How can I determine the last placeholder before copying and ...

Bootstrap5: Left-aligned Navigation Bar Pills and Right-aligned Text

I am trying to align all my navigation pills to the left, and then add a single text element that stays at the end of the navbar even when the page is resized. Navbar Image My attempt involved adding a div so that the navbar pills would take up 50% width ...

Ajax response values overlap

I am developing an application that requires multiple Ajax requests, but I encountered a problem where I am receiving the same response values for both requests. Each request must include a data field called activityCode, yet I keep getting the value of Sc ...

Can JavaScript be used to continuously monitor a window variable object in real-time?

Is there a way to dynamically control a variable in JavaScript? I'm currently working on a code that needs to display a button when it reaches the last signature of an automatic request process. The code for activating/deactivating the button is show ...

Conquering the need for a 426 upgrade was a challenging task

For the past few months, I have been diligently working on a web application with Angular for the front end and Node/Express/Mongo for the backend. My setup involves running Angular on localhost:4200 and Node on localhost:3000. However, some members of ou ...

What is the best way to securely store JWT refresh tokens on both the front-end and back-end?

Storing the refresh token on the client side in "Local Storage" poses a significant security risk. If a hacker gains access to this token, they could potentially have everlasting access to the user's account by continually refreshing both access and r ...

What is the best way to change the status of a disabled bootstrap toggle switch?

I'm working with a read-only bootstrap toggle that is meant to show the current state of a system (either enabled or disabled). The goal is for it to update every time the getCall() function is called. However, even though the console logs the correct ...

I am able to see the Redux props showing up in Redux DevTools, but for some reason they are not

I am facing an issue where I am passing a Redux prop to a component that is fetched from a payload. The payload successfully updates the state in my reducer and the component receives the prop (an array of objects fetched in the action) according to my Red ...

Developing and integrating views within a node-webkit desktop application

For my file copier desktop application built with node webkit, I aim to create a seamless flow where the initial check for existing profile data determines the first page displayed. The header with static links/buttons to various views remains consistent ...

The interaction between jQuery and Rails through ajax calls

Attempting to work with basic functionality, Sending a request with data and receiving a response with data, then displaying it using jQuery and Rails This piece of code pertains to the frontend. $("#internal_btn").click(function() { //windo ...

Passport.socket.io cannot resolve the issue of a missing session

The Issue I am facing a problem with the failed connection to socket.io: No session found using passport.socketio.js and I am unable to identify the root cause. Despite checking similar posts, the configuration seems fine to me. However, it appears that ...

How can I create a Material ui Card with a border-less design?

After reviewing the information provided, I noticed that you can set the option to have it as variant="outlined" or raised However, I am curious if there is a method to create the card without any visible borders at all? ...

How can I interact with a v-dialog component within a child component in Vue.js using Vuetify?

Exploring Vue.js for the first time and hoping to display a login dialog upon button click. To maintain cleanliness in my code, I shifted the dialog to a child component within a parent component with nested LoginDialog. Below are snippets of the parent co ...

Is there a newer alternative to the jQuery UI Draggable component available?

In search of draggable/sortable functionality for my .NET Razor Pages application. Came across the jQuery UI Draggable/Sortable component which I've used years ago with success. However, it's mentioned on the download page that the component is ...

The image is experiencing difficulty loading from the Express static directory

Having some trouble with image loading... I've noticed that images are loading fine from the local folder, but not from the uploads folder which is set to be static. I've been attempting to upload a file from the browser. The upload and save pr ...