Troubleshooting Angular 4's ng-selected functionality

I'm currently facing an issue with getting ng-selected to function properly. Initially, I attempted to simply add selected in the option tag, but later discovered that I should be using ng-select. Despite trying variations such as ng-selected="true" and ng-selected="selected", none have been successful. I've also explored recommendations from other stackoverflow posts without finding a solution. Interestingly, the feature did work at one point (in another HTML form where I encountered the same problem), but suddenly stopped.

<div class="col-lg-6">
  <div class="panel panel-default">
    <div class="panel-heading">Caloric Intake Recommendation</div>
    <div class="panel-body">
      <form [formGroup]="myForm" (ngSubmit)="onSubmit()">
        <div class="form-group row">
          <label for="weight" class="col-lg-2 col-form-label">Weight</label>
          <div class="col-lg-10">
            <input
                type="number"
                class="form-control"
                id="weight"
                formControlName="weight"
                placeholder="Weight">
          </div>
        </div>
        <div class="form-group row">
          <label for="goal" class="col-lg-2 col-form-label">Goal</label>
          <div class="col-lg-10">
            <select class="form-control" formControlName="goal" id="goal">
              <option ng-selected="selected">Lose Weight</option>
              <option>Maintain Weight</option>
              <option>Gain Mass</option>
            </select>
          </div>
        </div>
        <button
            class="btn btn-primary"
            type="submit"
            [disabled]="!myForm.valid">Submit
        </button>
        <hr>
        <div class="col-sm-4">
          <label class="col-sm-2 col-form-label">Your Recommended Protein:</label>
          <input type="text" value={{this.protein}}>
        </div>
        <div class="col-sm-4">
          <label class="col-sm-2 col-form-label">Your Recommended Carbs:</label>
          <input type="text" value={{this.carbs}}>
        </div>
        <div class="col-sm-4">
          <label class="col-sm-2 col-form-label">Your Recommended Fats:</label>
          <input type="text" value={{this.fat}}>
        </div>
      </form>
    </div>
  </div>
</div>

Component

import {Component} from "@angular/core";
import {FormControl, FormGroup, Validators} from "@angular/forms";
import {CaloricIntakeClass} from "./caloric-intake.class";

@Component({
  selector: 'app-caloric-intake',
  templateUrl: './caloric-intake.component.html',
  styleUrls: ['./caloric-intake.component.css']
})
export class CaloricIntakeComponent{
  myForm: FormGroup;
  caloricIntake: CaloricIntakeClass;
  weight: number;
  goal: string;
  protein: number;
  carbs: number;
  fat: number;


  onSubmit() {
    this.weight = this.myForm.value.weight;
    this.goal = this.myForm.value.goal;
    this.myForm.reset();

    this.caloricIntake = new CaloricIntakeClass(this.weight);
    if (this.goal === 'Cutting'){
          this.caloricIntake.cuttingIntake();
    } else if (this.goal === 'Bulking'){
          this.caloricIntake.bulkingIntake();
    } else {
          this.caloricIntake.maintaingIntake();
    }
    this.protein = this.caloricIntake.getProtein();
    this.carbs = this.caloricIntake.getCarbs();
    this.fat = this.caloricIntake.getFat();
  }

  ngOnInit() {
    this.myForm = new FormGroup({
      weight: new FormControl(null, Validators.required),
      goal: new FormControl(null, Validators.required)
    });
  }
}

Answer №1

Ensure that in your template, the ng-selected attribute of your option is linked to a variable named 'selected'. This means that within your component, you must initialize this variable as true from the start, for example:

export class CaloricIntakeComponent{

    selected : boolean;

    ......

    ngOnInit() {
        this.selected = true;
        ......

    }

}


Update

Verify that you have assigned values to the options, like so:

<select class="form-control" formControlName="goal" id="goal">
    <option value="lose_weight">Lose Weight</option>
    <option value="maintain_weight">Maintain Weight</option>
    <option value="gain_mass">Gain Mass</option>
</select>

In this case, it is not necessary to use ng-selected at all. Simply set your custom values directly in the component.

ngOnInit() {
    this.myForm = new FormGroup({
        weight: new FormControl(null, Validators.required),
        goal: new FormControl("lose_weight", Validators.required)
    });
}

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

Stream of information that triggers a specific action based on a specified condition

I'm dealing with an observable stream where I need to make two calls after retrieving the initial object using two id's found within the object. One of these id's, siteId, is optional and may or may not be present. If it is present, I need t ...

Django-oauth2 encountered a 500 error due to the presence of unauthorized URL query parameters in the request

Just starting out with django. Using: oAuth2 + PKCE protocol, Angular, Django-oauth2-toolkit + REST Continuously receiving this error: oauthlib.oauth2.rfc6749.errors.InvalidRequestError: (invalid_request) URL query parameters are not allowed <oauthli ...

Adding elements to a page while it is running can be achieved using a variety

Working on a college project, I am developing a demo web-app in Angular. The goal is to implement a feature where clicking a button adds a new node to the DOM tree. In JavaScript, a simple solution would be: document.getElementById('ticket-container& ...

The table is not properly displaying within the parent scrolled div due to issues with the fixed positioning

Apologies for any language barrier. I am encountering an issue with a PHP page that includes a table meant to be displayed as position:fixed; however, it consistently appears above the scrollbars and does not stay within the parent div. View screenshot he ...

I encountered an issue where I could not successfully update a list pushed into an array using the push function. Despite attempting to update the list, I

export class ApproveComponent implements OnInit { @Output() public next: EventEmitter<any> = new EventEmitter<any>(); codes: any[] = []; selectedCode: any; this.Apiservice.komm.subscribe(data => { this.se ...

enigmatic issue arising in Angular/Node

Could someone please shed some light on what might be causing the issue in my code? Thank you in advance! webpack: Compilation Failed. My Angular CLI: 1.6.3 Node: 8.9.4 OS: Windows 32-bit Angular: 5.2.1 Error Message: ERROR in ./node_modules/css-loader ...

Detecting URL changes on new windows in Angular Typescript: How to do it?

I am currently working with the updated version of Angular 6. My task involves opening a new browser window based on user input, which includes a specific return URL. After the return URL is fully loaded, I need to access and extract a particular element f ...

Creating a div that spans the entire height from top to bottom

Currently, I am faced with the following scenario: <div id=area> <div id=box> </div> </div> <div id=footer> </div> The "area" div is situated in the center and has a width of 700px with shadows on both the right and ...

Ways to conceal a div element when the JSON data does not contain a value

If the value in "desc" is empty, then hide <div24> and <popup-desc>. html <div class="popup"> <div class="popup-top" style="background-color: '+e.features[0].properties.fill+';"> ...

As a newcomer to Javascript, I am currently working on developing a CRUD-based application and could use some assistance with implementing the Edit functionality

I am currently in the process of developing a Javascript CRUD application that showcases data within an HTML Table. I have successfully implemented the Create, Read, and Delete functions. However, for the Edit function, I am looking to display the data in ...

Include the window.innerWidth value in the initial GET request

When dealing with a server-side rendered app that has responsive styling based on window.innerWidth, the challenge lies in how to pass the client's screen size in the initial GET request for index.html. This is crucial so that the server can prepare a ...

Tips for incorporating the Sanitize library into Angular 6:

What is the most effective library for sanitization in Angular 6 to enhance security measures? Since injecting dependencies can be tricky, what are some recommended methods for implementing this in an Angular 6 project? ...

Design adaptable HTML backgrounds

Hello, I am working on a webpage that uses two background images. Here is the CSS I'm using: body{ background: url('<?=base_url();?>/assets/header_bg.png') no-repeat, url('& ...

I am looking to save the session value into the search box of the appTables application by utilizing jQuery

Is there a way to save the session value in the search box of appTables by using jQuery? <?php $session = \Config\Services::session(); ?> <script type="text/javascript"> $(document).ready(function () { var searc ...

Guide to deploying angular universal starter kit on IIS - Configuring the Client Server setup

Currently, I am attempting to deploy an Angular Universal project onto IIS. I have set up a virtual directory pointing to the dist folder which contains both client and server folders. You can see the structure in this image: enter image description here ...

Display a JSON object on a web browser

I am trying to display a JSON object on a web browser using HTML. The object is already in a text file and has been properly formatted for readability. My goal is to maintain the same formatting when displaying it on the browser. ...

Resetting the datetime-local input to its initial value (ngModel) in template forms

In my Angular 6 template form, the user can modify the date/time in the datetime-local input after loading it with the latest data. However, I am struggling to reset the input back to the original date/time (loaded from array "one.classTimesLogOffRevised") ...

When hovering over A, the DIV element fails to appear

I'm encountering an issue with a specific page on my website () The problem lies with a .dropdown class that is supposed to display a DIV right below the header. In the source code, you can find it underneath <-- START DROPDOWN MENU -->. When I se ...

Why isn't my Visual Studio updating and refreshing my browser after making changes to the Angular project?

Having added an Angular project and running it successfully with ng serve / npm start, I encountered an issue. After making changes to the project and saving them using ctrl+s or file/all save, the project server did not recompile and the browser did not ...

The height and alignment of the <a> tag and <p> element vary within a flex container

Currently, I am in the process of constructing a bottom navigation bar for a blog page. This navigation bar will allow users to easily navigate between the last blog entry, the main blog home/index, and the upcoming post. However, when the user reaches the ...