Chaz Ashley
Chaz Ashley

Reputation: 409

Selected value isn't displayed while using ngModel

I have a simple component that doesn't set values of select, instead I write values in HTML

<select name="select1" ngModel id="s1" class="form-control">
  <option value="Item 1">Item 1</option>
  <option value="Item 2">Item 2</option>
  <option value="Item 3" selected>Item 3</option>
  <option value="Item 4">Item 4</option>
  <option value="Custom Item 1">Custom Item 1</option>
</select>

The selected option has value Item 3, but this value isn't displayed when I open my page. Without ngModel it's displayed. It also is displayed when I press an reset button (just an input with type="reset").

I have the same problem with checkboxes, radio buttons and simple text inputs as well, but in this case I use checked to display default value of radio buttons and checkboxes, and set value="default value" in case of text inputs.

Here is the ts file.

import { Component, OnInit, Output, Input, EventEmitter } from '@angular/core';
import {NgForm} from '@angular/forms';

@Component({
  selector: 'app-sidebar',
  templateUrl: './sidebar.component.html',
  styleUrls: ['./sidebar.component.css']
})
export class SidebarComponent implements OnInit {

  @Input() show: boolean;
  @Output() hideFiltersEvent = new EventEmitter();

  constructor() { }

  ngOnInit() {
  }

  onSubmit(aForm: NgForm){
    console.log(aForm);
  }
  onHideFilters(){
    this.hideFiltersEvent.emit();
  }
}

There is some methods in this file, but they have nothing to do with setting or reseting the form controls.

How to display default values of form controls without removing ngModel, if it's possible, and why all this happens?

Upvotes: 0

Views: 47

Answers (2)

Chaz Ashley
Chaz Ashley

Reputation: 409

In the case of radio buttons I had to use two-way binding with ngModel and the variable that contains the value of the checked button. Each radio buttons has to has such binding.

<input type="radio" name="radio1" [(ngModel)]="opt1" class="form-check-input" value="Option 1"/> Option 1

here opt1 is a string "Option 2" and the button is unchecked, but a similar radio button with value of Option 2 will be checked.

In the case of checkboxes I had to do the same, but a variable should has a boolean value, true - checked, false - unchecked.

Upvotes: 0

BeetleJuice
BeetleJuice

Reputation: 40936

Set the default value in your component class

currentValue = "Item 3";

And bind that value to the input using ngModel in your template:

<select name="select1" [(ngModel)]="currentValue">

When the template opens the starting current value will be shown as the default.

Upvotes: 1

Related Questions