Angular ngModel

ts:


import { Component } from '@angular/core';



@Component({

  selector: 'my-app',

  templateUrl: './app.component.html',

  styleUrls: [ './app.component.css' ]

})

export class AppComponent  {

  levelNum:number;

  levels:Array<Object> = [

      {num: 0, name: "AA"},

      {num: 1, name: "BB"}

  ];



  toNumber(){

    this.levelNum = +this.levelNum;

    console.log(this.levelNum);

  }



  selectedLevel = this.levels[0];



  selectedLevelCustomCompare = {num: 1, name: "BB"}



  compareFn(a, b) {

    console.log(a, b, a && b && a.num == b.num);

    return a && b && a.num == b.num;

  }

}

html:


<h1>Selecting Number</h1>

<select type="number" [(ngModel)]="levelNum" (ngModelChange)="toNumber()">

  <option *ngFor="let level of levels" [ngValue]="level.num">{{level.name}}</option>

</select>

{{levelNum}}



<hr>



<h1>Selecting object</h1>

<select type="number" [(ngModel)]="selectedLevel">

  <option *ngFor="let level of levels" [ngValue]="level">{{level.name}}</option>

</select>

{{selectedLevel | json}}



<hr>



<h1>Selecting object with custom compare</h1>

<select type="number" [(ngModel)]="selectedLevelCustomCompare" [compareWith]="compareFn">

  <option *ngFor="let level of levels" [ngValue]="level">{{level.name}}</option>

</select>

{{selectedLevelCustomCompare | json}}

Leave a Comment