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

Conceal a particular object from view by selecting it from the menu

I want to hide a specific element when the burger button is clicked. (See CaptureElementNoDisplay.PNG for the element to hide) When I click the burger button again to close the menu, I want the hidden item to be displayed once more. I've successfull ...

When I remove the `return false` statement in my code, my AJAX call executes successfully. However, keeping it in prevents the call from

I am using jQuery to send an AJAX POST request without refreshing the page. I have tried using the return false command to prevent the page from refreshing, but then the AJAX POST request doesn't go through. If I remove the return false command, the A ...

Ensure the inferred type is asserted in TypeScript

Is there a more elegant approach to assert the type TypeScript inferred for a specific variable? Currently, I am using the following method: function assertType<T>(value: T) { /* no op */ } assertType<SomeType>(someValue); This technique prov ...

The issue of jQuery not functioning properly within a Rails environment

Despite my efforts, I am still struggling to make jquery work in rails. I have installed the 'jquery-rails' gem and added the require statements in the application.js file. Below is a sample test page that I have been testing: <!DOCTYPE htm ...

Switch the website title as soon as the user looks away from the tab

How can I capture the user's attention and bring them back to my website when they are on a different tab? I really like the effect used on sephora.pl where an alert pops up with the message 'What are you waiting for?' when you switch tabs. ...

Update the component to display the latest information from the Bryntum grid table

In the Vue component, I have integrated a Bryntum grid table along with a bar chart. Clicking on one of the bars in the chart should update the data displayed in the Bryntum grid table. However, I've encountered difficulty in reloading the entire Bryn ...

jQuery load() issue

$('form.comment_form').submit(function(e) { e.preventDefault(); var $form = $(this); $.ajax({ url : 'inc/process-form.php', type: 'POST', cache: true, data:({ comment ...

Switch Button Hyperlink in HTML/CSS

I have the following code: document.addEventListener("DOMContentLoaded", function(event) { (function() { requestAnimationFrame(function() { var banner; banner = document.querySelector('.exponea-banner3'); banner.classList ...

Implementing a Map in Typescript that includes a generic type in the value

Here is a code snippet I am working with: class A<T> { constructor(public value: T) {} } const map = new Map(); map.set('a', new A('a')); map.set('b', new A(1)); const a = map.get('a'); const b = map.get(& ...

Creating a TypeScript interface that has keys determined by the elements in an array

My goal is to create a function that returns a record with keys specified by a string array. For example: // return type -> { itemA:SomeType,itemB:SomeType } const res = doThing(['itemA', 'itemB']) Do you think this is achievable? ...

Issue with conditional image source URL in NUXT component not functioning as expected

I am currently attempting to dynamically render an image source path based on the provided prop in the component. In case the image does not exist in the assets folder, I want to include a fallback path. Below is the code snippet for my image tag: <img ...

Exceed the capacity of a React component

Imagine having a React component that can render either a <button>, an <a>, or a React Router <Link> based on different props passed to it. Is it possible to overload this component in order to accept the correct props for each scenario? ...

Steps for incorporating the getElementByClassName() method

I have developed an application that features a list displayed as shown below: https://i.stack.imgur.com/BxWF2.png Upon clicking each tick mark, the corresponding Book name is added to a textbox below. I desire the tick mark to be replaced by a cross sym ...

What is the method to modify the background color of el-pagination?

I am using el-pagination on a dark page and I want to make its background color transparent. When I do not use the 'background' prop, the background color of el-pagination is white. Here is how it looks: (sorry I can't add an image) htt ...

Can you explain the distinction between the navigate function and routerLink feature in Angular 2?

As I go through the official Angular 2 tutorial, I noticed that it demonstrates using the navigate function in a way similar to routerLink. Can you explain the differences between these two methods and when it is best to use each? this.router.navigate([ ...

Installing material-ui using npm does not always result in getting the most up-to-date version

I'm currently facing a dilemma with an abandoned project that serves as the admin tool for my current project. The Material-UI version used in this project is 0.19.4. However, when I remove the dependency from my package.json file and execute npm inst ...

What is the best way to dynamically incorporate Before After CSS code in Vue?

I am facing a unique challenge in my current project. I need to dynamically apply colors from data inside a v-for loop, specifically for the :after CSS pseudo-element. While normal CSS properties are easily applicable, I am struggling with applying styles ...

Tips for creating a plug-in plugin and applying the necessary parameters

(function( $ ){ var functions = { init : function( options ) { var settings = $.extend({ //Declaring default settings that can be overridden in the plugin call code: 7, listHe ...

Replicate the functionality of a backend API using AngularJS

Currently, I am in the midst of creating a GUI for an application that is still undergoing API development. Although I have a vision of how it will look, it lacks functionality as of now. Hence, I need to replicate its behavior until the API is fully funct ...

The outcome of using Jest with seedrandom becomes uncertain if the source code undergoes changes, leading to test failures

Here is a small reproducible test case that I've put together: https://github.com/opyate/jest-seedrandom-testcase After experimenting with seedrandom, I noticed that it provides consistent randomness, which was validated by the test (running it multi ...