Angular 8 does not show the default option in the select tag

When I use the following code snippet:

<div style="text-align:center">
  <form>
    <select
      type="checkbox"
      name="vehicle1"
      (change)="onchange()"
    >
      <option>
        1
      </option>
      <option>
        2
      </option>
    </select>
  </form>
</div>

everything works fine, with the select defaulting to the first option. But when I modify it like this:

<div style="text-align:center">
  <form>
    <select
      type="checkbox"
      name="vehicle1"
      [(ngModel)]="selectValue"
      (change)="onchange()"
    >
      <option [ngValue]="1">
        1
      </option>
      <option [ngValue]="2">
        2
      </option>
    </select>
  </form>
</div>

export class AppComponent {
  title = "CodeSandbox";

  public selectValue = "1";

  constructor() {}

  onchange() {
    console.log("onchange");
    console.log(this.selectValue);
  }
}

by adding ngmodel and ngValue, the select tag shows up empty by default.

I am aware that I could add a line to display a dropdown title like:


 <option [ngValue]="'none'" disabled>Select SortType</option>

however, I do not want that. I want the first option to be displayed by default. Is there any way to achieve that?

Here is my sample code

Answer №1

If you utilize [ngValue], make sure it is interpreted as a number rather than a string

To address this, consider modifying it to [ngValue]="'1'" or adjusting public selectValue = 1;

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

Issue: When attempting to read the length of a property in Angular 6, a TypeError is being thrown because the property is

Unable to retrieve values from an array using the TS code below: this.dataservice.get("common/public/getAllCategories", null).subscribe(data => { //console.log('categories'+JSON.stringify( data)); this.categoriesarray = data; }); var ...

The installation of @angular/router seems to have encountered an error

I am attempting to update my @angular/router dependency from version 2.0.0 to 3.0.0-alpha.7. I have included it in my package.json file. { "name": "angular2-quickstart", "version": "1.0.0", "scripts": { "start": "tsc && concurrently &bs ...

What exactly is the concept behind the Strategy OnPush?

I am a beginner in the world of Angular2 with TypeScript. As I delve into my project, one concept that continues to elude me is the purpose of OnPush: changeDetection : ChangeDetectionStrategy.OnPush Despite my dedicated efforts in researching this top ...

Is it possible to assign a string literal type as a key in TypeScript mappings?

Is it possible to map a string literal type as a key in a new type? I attempted this, but it did not work as expected. const obj = { type: "key", actions: { a() {}, b() {}, }, } as const; /* Map to { key: { a() {}, b() {}, } */ t ...

Imported modules are not being blocked by APP_INITIALIZER

In my Angular application (version 6.0.0), I am working on setting up runtime configuration using APP_INITIALIZER to pull in the configurations. While consulting various articles and Stack Overflow questions, such as this one and that one, I have managed t ...

Exploring the intricacies of pattern matching with JavaScript visualization

I am currently working on improving my pattern matching function by creating a visualizer for it. To achieve this, I need to slow down the execution of each comparison. My approach involves declaring the i and j variables outside of the function so that I ...

How can you obtain the user ID by verifying an email when using applyActionCode in Firebase 9 modular?

Is there a way to access the UID of an email verified user? Will the response provide any helpful insights, or should I handle this from another source? const handleVerifyEmail = (auth: any, actionCode: any) => { applyActionCode(auth, actionCode! ...

Setting the base href in Angular using an environment variable for a Tomcat or other application server - a step-by-step guide

Is it possible to set the base href using an environment variable in a Tomcat or application server? For instance: index.html <base href="/${environment.tomcat}/"> Or is there a way to utilize an environment variable for the operating system? ...

The Angular HTML component is failing to display the locally stored JSON data upon page initialization

import { Store,STORES } from '../models/store'; export class StoreLocatorComponent implements OnInit { public Stores: any = []; constructor() { } ngOnInit(): void { this.Stores = STORES ; this.Stores.forEach(element => { ...

Validate the presence of a value in AngularFire and if not found, proceed to create it

I recently started using AngularFire, and since the update to AngularFire5, I've been encountering some issues. My goal is to create a 'room' with a unique id: name pair. When a user inputs a name, I need to check if that name already exists ...

Having trouble resolving the error "Cannot find name CSSTranslate" while working with VSCode and tsc? Let's tackle this issue together

My program runs smoothly in a development environment and appears flawless in VSCode, but I'm encountering issues with tsc pointing out unknown names and properties. It's puzzling because my file doesn't seem to have any problems in VSCode. ...

Using ngIf for various types of keys within a JavaScript array

concerts: [ { key: "field_concerts_time", lbl: "Date" }, { key: ["field_concert_fromtime", "field_concert_totime"], lbl: "Time", concat: "to" }, { key: "field_concerts_agereq", lbl: "Age R ...

Elastic Beanstalk hosted apps do not support the transmission of large files

I've been working on a web application that requires storing large files, specifically mp4 videos with sizes sometimes exceeding 100mb. However, I encountered an error when trying to upload these files from a static Angular website hosted in an S3 buc ...

Verify two asynchronous boolean variables and trigger a function if both conditions are met

Is there a way to enhance the rendering process so that the renderFilters() method is only called when both variables are true: These two variables are loaded asynchronously through 2 API methods: //getManager() this.isLoadingManager = true; //getPdiPOrg ...

making GET and POST requests within a single function using Angular 2

How can I trigger an HTTP POST service call after a successful GET response? This is how I've implemented the GET call: import {Page, NavController} from 'ionic-angular'; import {Http, Headers} from 'angular2/http'; import ' ...

Error: React - Unable to access the 'lazy' property because it is undefined

I used a helpful guide on the webpack website to incorporate TypeScript into my existing React App. However, upon launching the app, an error message pops up saying: TypeError: Cannot read property 'lazy' of undefined The version of React being ...

Creating an Angular 7 Template using HTML CSS and Javascript

I recently acquired a template that comes with HTML, CSS, and Javascript files for a static webpage. My goal is to integrate these existing files into my Angular project so I can link it with a Nodejs application to create a full-stack webpage with backend ...

Restrict Submission to Specific Values within Reactive Forms Enclosed in FormArray

Can someone help me with a problem I'm having? I need to figure out how to submit only selected values from my formArray when clicking the submit button. Specifically, I want to display just the ingredient_id and price in the console.log, while exclud ...

Is it possible for me to incorporate a portion of the interface?

Is it possible to partially implement an interface? export interface AuthorizeUser { RQBody: { login: string; password: string; }; RSBody: { authorizationResult: AuthorizationResult; }; }; class AuthorizeUserRQBody implements Authorize ...

md-input-container malfunctioning

I am facing an issue with the code using "@angular/material": "^2.0.0-beta.1" import { MaterialModule, MdIconRegistry, OVERLAY_PROVIDERS, MdInputContainer, MdInputDirective } from '@angular/material' .... <md-input-container> <i ...