angularngmodel

Angular select default value with ngModel not working on a select element but working on another


why is this working:

myComponent1.html

    <select  id="BisMonat" class="form-control" [(ngModel)]="currentmonatbis">
    <option [value]="01">Januar</option>
    <option [value]="02">Februar</option>
    <option [value]="03">März</option>
    <option [value]="04">April</option>
    <option [value]="05">Mai</option>
    <option [value]="06">Juni</option>
    <option [value]="07">Juli</option>
    <option [value]="08">August</option>
    <option [value]="09">September</option>
    <option [value]="10">Oktober</option>
    <option [value]="11">November</option>
    <option [value]="12">Dezember</option>
    </select>

myComponent1.ts:

export class myComponent1 implements OnInit
{
  currentmonatbis: number = new Date().getMonth()+1;

but this is not working:

myComponent2.html:

 <select  id="Weltanschauung" class="form-control" [(ngModel)]="weltanschauung">
  <option [value]="westlich">Westlich</option>
  <option [value]="koscher">Koscher</option>
  <option [value]="halal">Halāl</option>
  <option [value]="vegetarisch">Vegetarisch</option>
  <option [value]="vegan">Vegan</option>
</select>

myComponent2.ts:

export class myComponent2.ts implements OnInit
{
  weltanschauung: string = "koscher";

like its basically the same ??


Solution

  • When you use [value]="westlich", The compiler is searching for a variable named "westlich" but there is no variable like this. Use this:

     <select  id="Weltanschauung" class="form-control" [(ngModel)]="weltanschauung">
      <option value="westlich">Westlich</option>
      <option value="koscher">Koscher</option>
      <option value="halal">Halāl</option>
      <option value="vegetarisch">Vegetarisch</option>
      <option value="vegan">Vegan</option>
    </select>

    I.E Use the values with the [,]