Setting a default value for the dropdown in Angular is essential for ensuring a smooth

 <select [(ngModel)]="detail.State" (ngModelChange) ="onStateChange()" class="form-control">
              <option [ngValue]="null"  disabled selected>Select State</option>
              <option *ngFor="let option of stateData"  [ngValue]="option.KeywordValueText">{{option.KeywordValueText}}</option>
            </select>  

 <select [(ngModel)]="detail.City" class="form-control">
               <option [ngValue]="null"  disabled selected>Select City</option>
              <option *ngFor="let option of cityData" [ngValue]="option.KeywordValueText">{{option.KeywordValueText}}</option>
            </select>

In the .ts file, a function is defined as:

onStateChange() {
    this.detail.City = 'null';
    let selectedState = this.keywords.State.filter((val: { KeywordValueText: string | undefined; }) => val.KeywordValueText === this.detail.State);
    this.cityData = this.keywords.City.filter((val: { ParentID: any; }) => val.ParentID == selectedState[0].KeywordValueID);
  }

The requirement is to have default selections for both Choose State and Choose City. When the state is changed, the city should revert back to Choose City. Assistance in achieving this functionality is appreciated.

Answer №1

If a city is named "null," it's best to use the value null instead of the string "null".

Your current HTML code correctly uses the value null, so make sure to set the values to null during initialization or in the ngOnInit function.

detail = { State: null, City: null };

Alternatively, you can do the following in the ngOnInit and onStateChange functions:

ngOnInit() {
  this.detail.State = null;
  this.detail.City = null;
}

onStateChange() {
  this.detail.City = null;
  ...
}

Don't forget to update the type of these properties to string | null.

You can view the Stackblitz example here: https://stackblitz.com/edit/angular-ivy-smprf2?file=src/app/app.component.ts


If you prefer to use the string value, simply remove the square brackets from your HTML or add single quotes to avoid causing the string to be read as JS.

<option ngValue="null" ...>

OR

<option [ngValue]="'null'" ...>

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

Angular 2's updated router feature, routerCanReuse, provides improved functionality

I'm curious about the changes in the Angular 2 router, particularly the removal of the CanReuse interface. Is there another feature in the router that can achieve the same functionality of forcing a component reload? ...

Exploiting the Power of useRef with TypeScript in Functional Components of React

I'm having trouble accessing the child component method from the parent component using useRef. Eventually, the SayHi method will be responsible for updating the hook state in the child component. Unfortunately, I am encountering some bugs that I can ...

Is there a way to adjust this validation logic so that it permits the entry of both regular characters and certain special characters?

Currently, the input field only accepts characters. If any other type of character is entered, an error will be thrown as shown in the code below. How can I update this logic to allow not only letters but also special characters like hyphens and apostrop ...

Despite being logged, the current value of firebase.auth().currentUser in Firebase is null

I have coded a query in my service.TS file that displays the "state" of items based on the UID of the logged-in user: getLists(): FirebaseListObservable<any> { firebase.auth().onAuthStateChanged(function(user) { if (user) {console.log("blah", fir ...

Issues arise during the deployment of Angular7 production build when passing through the Bitbucket package manager

I am working on a project to create a system that allows Angular components to be reused across multiple applications via BitBucket. Currently, I have the following setup: BitBucket Repo A - This repository stores the node module. The module is develope ...

Are child routes permitted to be utilized without the need for router outlets, specifically for tab contents within a main component?

Can different components be rendered for each tab in a tab menu without using router outlets? Within my parent component, there is a template containing a tab menu component with each tab item having an ng template associated with it. I have set the tabs p ...

Ways to display varied JSON information on a component in Angular 4

I am facing a challenge with a reusable component that fetches data from a JSON file. I want to customize the data displayed when this component is used as a subcomponent within other components. For example, let's say we have a Banana component: @U ...

Upgrading to React Router v6: Implementing Loader Functions with Context API

Having issues implementing loaders in React-Router V6 while making a request for a page through a function located in the context file. Unfortunately, I can't access the context from main.js where the router is defined. Main.js import ReactDOM from & ...

When you hover over nested HTML-lists in a webpage, make the tree's long text lines expand gracefully using a combination of HTML, CSS

In my Angular 4 application, I have a left div that displays a tree of items as recursive HTML lists. When there is a long text, it gets cut off by the border of the div and a scrollbar appears. I want to have the text expand beyond the border and show in ...

The PrimeNG p-datatable is failing to detect the template that was given

In one of my scenarios, I have a table with varying numbers of rows and columns. Unfortunately, I do not have any information about the header names for this table. To tackle this issue, I have implemented the following approach: Firstly, I obtain the re ...

Exploring the world of TypeScript interfaces and their uses with dynamic keys

I am hopeful that this can be achieved. The requirement is quite simple - I have 2 different types. type Numbers: Number[]; type Name: string; Let's assume they are representing data retrieved from somewhere: // the first provider sends data in th ...

Combine arrays of objects by comparing two attributes in Typescript

Suppose I have an array in TypeScript that looks like this: const array = [ { id_m: "123", period: "Q1/22", amount: 1000 }, { id_m: "123", period: "Q1/22", amount: 500 }, { id_m: "123&q ...

Having trouble retrieving data from a JSON file within an Angular application when utilizing Angular services

This JSON file contains information about various moods and music playlists. {mood: [ { "id":"1", "text": "Annoyed", "cols": 1, "rows": 2, "color": "lightgree ...

When utilizing the useRef hook in Material-UI, an error may arise stating: "The property 'value' is not found on the type 'never'."

Currently, I am utilizing material UI to construct a login and registration page. In the process, I am leveraging the useRef hook to retrieve a reference instance for a TextFiled, and using xxxRef.current.value to access the input value. Despite being abl ...

Personalize the md-tab component in Angular 2

I'm encountering an issue with styling the md-tab component in Angular 2. While I understand that Angular 2 Materials is currently under development, I am wondering if there is a way to customize it, such as removing the bottom-radius. Below is an exa ...

Utilizing Angular Firestore in Combination with Await

Upon reviewing this response, I attempted to implement async/await with a firestore call but it seems like I may be overlooking something. The aim is to fetch a collection of 'hex' documents for a hex grid using Snapshot. Initially, I had valueC ...

Encountering a reload error while refreshing the Angular page

Whenever I click on a deck from my list, the corresponding deck-detail component is supposed to load and display the details of the selected deck. The URL should also change to something like "deck/id/deckName". However, if I try to reload the page or copy ...

Steps for utilizing field labels to transmit values in Protractor

Could someone offer guidance on how to send values using field labels? I understand that it's generally not recommended to use labels for sending values since they can change, but in my case, the labels remain constant. I have attached screenshots of ...

Updating data within rows in Angular 4

Is there a way for me to update the value in my row based on a selected ingredient from a dropdown list? I want the unit price to be patched into the input field when a specific ingredient is chosen. You can find the relevant code snippets by visiting TH ...

Transferring information from a service to a parent component, and subsequently passing it to a child component

Hello everyone, I am a beginner with Angular and I seem to have run into an issue that I can't figure out. In my parent component, I am attempting to pass the weekly variable to my child component but it doesn't seem to be working as expected. H ...