Updating select options list dynamically in Angular

In a modal, I have two selects that are populated with data from two different object arrays:

<select class="browser-default" id="gebied" 
  [(ngModel)]="filteredGebied" 
  (ngModelChange)="onChange($event)">
    <option *ngFor="let gebied of list1" 
      value="{{gebied.id}}">{{gebied.beschrijving}}</option>
</select>

<select class="browser-default" id="domein" [(ngModel)]="filteredDomein">
  <option *ngFor="let domein of list2"
    value="{{domein.id}}">{{domein.beschrijving}}</option>
</select>

My goal is to dynamically update the options in the second select based on the selection made in the first select.

onChange(list1Id){ 
...
this.list2 = ...
}

However, I am facing an issue where the options in the second select do not update as expected.

Sometimes, an error occurs stating:

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'ngForOf:

How can I resolve this problem and make the necessary changes?

Answer №1

Ensuring optimal functionality is key. For instance, I verify if a is chosen, indicating that based on your binding, filteredGebied equals 1, then it follows that list2 should be updated!

  export class AppComponent {
      list1 = [{ id: '1', description: 'a' }, { id: '2', description: 'b' }];
      list2 = [{ id: '1', description: 'aaa' }, { id: '2', description: 'bbbb' }];
      filteredArea;
      filteredDomain;

      onChange(event) {
      if (this.filteredArea === '1') {
        this.list2 = [{ id: '1', description: 'xxx' }, { id: '2', description: 'yyyy' }];
      }
     }
   }

Answer №2

It seems to be functioning when I refrain from loading the second select initially. However, this does not pose an issue for my specific application.

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

When attempting to start the Azure Functions within a Nodejs Monorepo, the runtime fails with an error

My setup involves a nodejs typescript monorepo structured as follows: libraries/ lib1/ lib2/ package.json tsconfig.json web-api/ function1/ function.json index.ts function2/ function.json index.ts host.json package.json ts ...

Angular 6: Utilizing async/await to access and manipulate specific variables within the application

Within my Angular 6 application, I am facing an issue with a variable named "permittedPefs" that is assigned a value after an asynchronous HTTP call. @Injectable() export class FeaturesLoadPermissionsService { permittedPefs = []; constructor() { ...

Learn how to enhance a Vue component by adding extra properties while having Typescript support in Vue 3

Attempting to enhance a Vue component from PrimeVue, I aim to introduce extra props while preserving the original components' typings and merging them with my new props. For example, when dealing with the Button component that requires "label" to be ...

Mapping JSON to interface in Angular 7: A step-by-step guide

I am currently working with angular7 and I have a requirement to map a json object to my interface. My goal is to create a function that can accurately map the fields of the json object to the corresponding properties in the interface. Additionally, if the ...

Break down the key:value objects into individual arrays

I'm currently working on an ionic project that involves handling an incoming array composed of key:value objects such as the one shown in the image below: https://i.stack.imgur.com/qrZiM.png My question is, can these values be separated into three d ...

Searching through an array of objects with ng2-completer does not yield any search results

Having some trouble with the ng2-completer plugin when trying to enable auto-complete functionality in a search box. The issue arises when attempting to use an array of objects instead of just strings, resulting in a 'No Results found' message. E ...

Can you choose to declare a type in TypeScript, or is it required for every variable

Has anyone encountered a problem similar to this? type B = a ? 'apple' | 'grape' | 'orange' : 'apple' | 'grape'; // This code results in an ERROR! const x = (a: boolean, b: B) => console.log('foo&a ...

Overflow issue occurs in react-bootstrap when a Table is placed within the Card.Body

Looking to design a responsive table with a row details section inside a card using react bootstrap. I have applied different colors to the sections for better visual understanding. However, I am facing an issue where the card body slightly overflows the ...

Typescript feature: Configuring BaseUrl with nested directories

When utilizing the 'baseUrl' property along with the 'paths' property in this manner: "baseUrl": "./src", "paths": { "app-component": [ "app/app.component"], "test-component": [ "app/test/test.component" ] } the compilation proces ...

Best practice for importing ts files from an npm package

When faced with the need to divide a ts project into multiple repositories/packages for creating microservices, the challenge arises in combining these packages efficiently. Some packages are required in one microservice, others in another, and some in all ...

Using Angular: How to access a component variable within a CSS file

I'm having issues with my css file and attempting to achieve the following: .login-wrapper { background-image: url({{imagePath}}); } Below is my component code: export class LoginComponent implements OnInit { imagePath: any = 'assets/discord ...

Display a notification next to the pinned location on the map using the Google Maps API

I'm trying to get this popup to show up close to the marker. Can anyone help me figure out how to do it? Here is my current setup: .html <agm-map [latitude]="lat" [longitude]="long" style="height: 350px;" [fitBounds]="true"> <agm-marker ...

Steps for associating ngclass with an observant value

Can you bind to an Observable<enum> like this in Angular? <a [ngClass]="{selected: (mapToolBarMode$ | async) === 0 }" /> or <a [ngClass]="{selected: (mapToolBarMode$ | async) === MapMode.Pan }" /> where the observable is named mapTool ...

The value of 'useFonts' cannot be changed as it is a read-only property in expo-fonts

Struggling with 'useFonts' being read-only and unable to assign In my Expo project using React Native (TypeScript), I encounter the issue of trying to import a .ttf font file. My attempt was to create a custom hook called "useFont" to pre-load ...

Is there a way to trigger an error event in Jest using TypeScript?

As an illustration, let's take a look at how I'm utilizing Archiver: archive.on('error', err => { if (typeof callback === 'function') { callback.call(this, err); } else { throw err; } }); It appears that the ...

'Error: Script ngcc is missing in NPM' - Issue encountered

Out of nowhere, my Visual Studio Code project suddenly began showing two strange errors like this: click to view image All the tags from Angular Material are now being marked as errors, failing to get recognized as valid tags. Attempting to use npm run n ...

What's the Best Way to Add a Custom Flag to the `nx angular serve` Command Without Triggering an Error?

When running the nx angular serve command, I want to add my custom flag (-t example). But when I try this, I get an error message from nx that says: 't' is not found in schema To address this issue, I plan to capture this flag in proxy.mjs an ...

How to capture a screenshot of the current screen using Nativescript programmatically

After taking a screenshot in a NativeScript app, is there a way to display a popup asking if the user wants to save the picture? I attempted using the 'nativescript-screenshot' plugin, but it only copies elements within the application: nat ...

Is it possible to navigate to the Angular component that defines a tag in VSCode by simply clicking on the tag?

In my current Angular project in VSCode, I often find myself wanting to delve deeper into specific tags that I encounter while coding. For instance, if I stumble upon a tag like <display-active-users>, I usually have to go through the process of sea ...

Creating several light beams from a rotated structure

My current challenge involves shooting multiple rays from a rotating mesh in various directions targeting points on a circle divided by the number of rays. To assist with debugging, I have added ArrowHelpers for each ray with a goal for the arrows to turn ...