Updating Select Options Disabled/Enabled in Angular 2

In my Angular2 project, I have 2 select elements:

<div ng-controller="ExampleController">
<form name="myForm">
<label for="companySelect"> Company: </label>
<select name="companySelect" id="companySelect">
  <option *ngFor="let company of companies" 
           value="{{company.id}}"> {{company.name}}
  </option>
</select>

<label for="documentTypeSelect"> Type: </label>
<select name="documentTypeSelect" id="documentTypeSelect">
  <option value="type1">type1</option>
  <option value="type2">type2</option>
  <option  value="type3">type3</option>
</select>
 </form>
 <hr>
</div>

Is it possible to dynamically change the options of the second select based on the selection in the first select? This can be achieved by checking boolean values like:

company.companyRelations.pop().type1

company.companyRelations.pop().type2

If, for example, type1 is false, the option in the second select should be disabled and if type2 is true, the option should be enabled.

EDIT:

The companies in the select have properties such as desadv, invoic, and orders, which are either true or false. How can these properties be passed into component.ts properties?

company.companyRelations.pop().desadv

I want to retrieve the selected company's properties and use them to enable/disable options in the second select.

html

<form name="myForm">
<label for="companySelect"> Company: </label>
<select class="form-control" name="companySelect" id="companySelect" 
 [(ngModel)]="companySelect" (ngModelChange)="onChange($event)">
  <option [ngValue]="undefined" disabled  selected>Select...</option>
  <option *ngFor="let company of companies" [ngValue]="company.id">
 {{company.name}}</option>
</select>

<select  name="documentTypeSelect" id="documentTypeSelect">
  <option [ngValue]="undefined" disabled  selected>Select...</option>
  <option [disabled]="!desadv" value="desadv">desadv</option>
  <option [disabled]="!invoic" value="invoic">invoic</option>
  <option  [disabled]="!orders" value="orders">orders</option>
</select>
</form>

component.ts

  desadv: boolean = false;
  invoic: boolean = false;
  orders: boolean = false;

One approach to implementing this functionality could be:

  onChange(event) {
   if(event.desadv) {
     this.desadv = true;
   }
  }

My solution:

html

 <form name="myForm">
<label for="companySelect"> Company: </label>
<select name="companySelect" id="companySelect" [(ngModel)]="companySelect" 
(ngModelChange)="onChange($event)">
  <option [ngValue]="undefined" disabled  selected>Select...</option>
  <option *ngFor="let company of companies" [ngValue]="company">
{{company.name}}</option>
</select>

<label for="documentTypeSelect"> Type: </label>
<select  name="documentTypeSelect" id="documentTypeSelect">
  <option [ngValue]="undefined" disabled  selected>Select...</option>
  <option [disabled]="!desadv" value="desadv">desadv</option>
  <option [disabled]="!invoic" value="invoic">invoic</option>
  <option  [disabled]="!orders" value="orders">orders</option>
  <option  [disabled]="!recadv" value="orders">recadv</option>
  <option  [disabled]="!shipment" value="orders">shipment</option>
</select>

component.ts

 onChange(event) {
this.desadv = event.companyRelations[0].desadv;
this.invoic = event.companyRelations[0].invoic;
this.orders = event.companyRelations[0].orders;
this.recadv = event.companyRelations[0].recadv;
this.shipment = event.companyRelations[0].shipment;
}

Answer №1

Give this a try :

<select class="form-control" name="companySelect" id="companySelect" [(ngModel)]="companySelect" (ngModelChange)="onChange($event)">
    <option [ngValue]="undefined" disabled  selected>Select...</option>
    <option *ngFor="let company of companies" [ngValue]="company.id">{{company.name}}</option>
</select>

<select [disabled]="btnDisable" name="documentTypeSelect" id="documentTypeSelect">
  <option value="type1">type1</option>
  <option value="type2">type2</option>
  <option  value="type3">type3</option>
</select>

component.ts

private companySelect: any;
private btnDisable: boolean = true;

onChange(event) {
    if(event) {
        this.btnDisable = false;
    }
}

Answer №2

Absolutely possible! I've developed a demo where the second dropdown will be activated based on the value of the flag in the first dropdown object.

// Your code snippet goes here

var myApp = angular.module('plunker',[]);
angular.module('plunker').controller('MyCtrl', MyCtrl)
MyCtrl.$inject = ['$scope'];
function MyCtrl($scope) {
$scope.items1 = [{
id: 1,
label: 'aLabel',
'flag':true,
subItem: { name: 'aSubItem' }
}, {
id: 2,
label: 'bLabel',
 'flag':false,
subItem: { name: 'bSubItem' }
}];

$scope.items2 = [{
id: 1,
label: 'MyName',
'flag':true,
subItem: { name: 'aSubItem' }
}, {
id: 2,
label: 'YourName',
 'flag':false,
subItem: { name: 'bSubItem' }
}];

$scope.changeDetect = function(){
  $scope.selected1='';
  console.log($scope.selected);
  if($scope.selected.flag)
  {
    $scope.flagValue=false;
  } else {
    $scope.flagValue=true;
  }

}

$scope.flagValue=true;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js"></script>

<div  ng-app="plunker" ng-controller="MyCtrl">
   <select ng-options="item as item.label for item in items1 track by item.id" ng-model="selected" ng-change="changeDetect()"></select>
   
    <select ng-options="item as item.label for item in items2 track by item.id" ng-model="selected1" ng-disabled="flagValue"></select>
   </div>

For AngularJS 2

<select [ngModel]="selectedDeviceObj" (ngModelChange)="onChangeObj($event)" name="sel3">
    <option [ngValue]="i" *ngFor="let i of deviceObjects">{{i.name}}</option>
  </select>
 <select [ngModel]="selectedDeviceObj1" name="sel2" [disabled]="flag">
    <option [ngValue]="i" *ngFor="let i of deviceObjects1">{{i.name}}</option>
  </select>
onChangeObj(newObj) {
     this.selectedDeviceObj1='';
    console.log(newObj);
    this.selectedDeviceObj = newObj;
     if(newObj.flag){
      this.flag = false;
    }
    else {

      this.flag = true;
    }

To check out the demo, visit this Plunkr link

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

A guide on utilizing Angular service within a component to successfully submit form data to an API

I am currently facing an issue with my Angular 6 form and service setup. I have a service that can successfully handle GET requests to a web API, but I am struggling with making POST requests from my form to the API. The code I currently have is not workin ...

Clicked but nothing happened - what's wrong with the function?

For my project, I have incorporated tabs from Angular Material. You can find more information about these tabs here. Below is the code snippet I am using: <mat-tab-group animationDuration="0ms" > <mat-tab></mat-tab> < ...

Adding a specified number to a value in React: x + y

I am facing an issue with adjusting the value of deliveryFee based on the changing value of a variable weight. Initially, I have set specific values for deliveryFee based on different weight ranges: Up to 2 kg => $3.40 Up to 5 kg => $3.80 Up to 10 k ...

Issue with the code flow causing nested function calls to not work as expected

I'm experiencing an issue with my code: The problem arises when param.qtamodificata is set to true, causing the code to return "undefined" due to asynchronous calls. However, everything works fine if params.qtamodificata is false. I am seeking a sol ...

What is the best way to transform a string into React components that can be displayed on the screen?

Stored in my database are strings that contain partial HTML content, as shown below: “Intro<br /><br />Paragraph 1<br /><br />Paragraph 2” If I want to display this string within a new <p> element, what is a straightforwa ...

Avoid retrieving information from Firestore

Hey everyone, I'm struggling to figure out why I can't retrieve data from Firestore. Even after carefully reading the documentation and double-checking the path, I still can't seem to make it work. I'm working with Ionic framework. getC ...

Stopping Angular.js $http requests within a bind() event

As stated in this GitHub issue Is it expected to work like this? el.bind('keyup', function() { var canceler = $q.defer(); $http.post('/api', data, {timeout: canceler.promise}).success(success); canceler.resolve(); } ...

Obtain the template as a string within Vue

Let's examine the scenario of having a single file component in Vue with the following structure: // Article.vue <template> <div> <h1>{{title}}</h1> <p>{{body}}</p> </div> </template> If w ...

Using Next-auth.js: Redirecting from getServerSideProps to a specific callback URL - How can it be done?

Hey, I've been working on implementing authentication with the NextAuth library in my Next.js application. While following the documentation, I encountered a situation that wasn't covered. I'm attempting to create a 'route guard' o ...

Manually validate inputs in Angular

I've encountered an issue with the bootstrap datepicker. When I click on the date icon, the date and time automatically populate in the input field. However, the input remains invalid because I haven't directly interacted with it. Has anyone else ...

Using Angular 2+ to make an http-get request with parameters

I am looking to create a GET method with multiple parameters. Currently, my example works with one parameter but I need to add another. In the backend code segment below, you can see where I am trying to pass the second parameter, 'created_by', b ...

Issue with Angular 6: unable to make HTTP POST request from secondary dialog

I'm facing an issue when trying to send HTTP requests from a dialog window in Angular 6. Here's the scenario: I click a button to open the first dialog, then within that dialog I click another button to open a second dialog. In the second dialog ...

Differences between const and let when utilizing the require function

With io.js now offering ES6 support, you can finally take advantage of the powerful const and let keywords. While let is seen as the successor to var with added capabilities, what about const? We all know what "constant" means, but when is it best practice ...

How to Convert Python Lists into JavaScript?

octopusList = {"first": ["red", "white"], "second": ["green", "blue", "red"], "third": ["green", "blue", "red"]} squidList = ["first", "second", "third"] for i in range(1): squid = random.choice(squidList) octopus = random. ...

Disabling a chosen option within a dropdown menu

`Hello there, I am just starting out with JavaScript and jQuery. Currently, I am developing a web application for ordering food and drinks. I have a dropdown menu for selecting breakfast items and the quantity. When the "add" button is clicked, a dynamic ...

Issues arise when upgrading from Angular 8 to 9, which can be attributed to IVY

After successfully upgrading my Angular 8 application to Angular 9, I encountered an error upon running the application. { "extends": "./tsconfig.json", "compilerOptions": { "outDir": ". ...

Encountering an issue with Typescript Vue class-based components in Laravel Mix: issue arises when attempting to set property 'render' on an undefined object

I have been using Laravel Mix to compile my Vue components, incorporating TypeScript and class-based components. Each class is exported from the component, and every component is required by the context in the main application script. However, during rende ...

Is it possible to change the background color of a MUI theme in ReactJS by using Css

Currently, I am utilizing Material UI to create a theme that is functioning correctly. However, upon adding <CssBaseline/> to the App.js file, it unexpectedly changes the background color to white instead of the intended #1f262a specified in the inde ...

Combining two JSON datasets using specific fields in Javascript

Two JSON inputs are provided: [ { userId: 32159, userFirstName: "john", userLastName: "doe", plans: [ ] }, { userId: 32157, userFirstName: "dave", userLastName: "mess", plans: [ ] } ] and [ { userId: ...

The command 'ng' for Angular is not being detected as a valid internal or external command, executable program, or batch file, preventing access to the Angular app from outside the localhost

Whenever I try to run "'ng' is not recognized as an internal or external command, operable program or batch file." with ng serve --host 0.0.0.0 from my command prompt, it gives me this error message. However, running it through the node.js comma ...