首页 > 解决方案 > Select box in does not bind to component.ts

问题描述

I am trying to bind my select box to a variable using this code:

TS FILE

public selectedPlaza: string;
plazaList: Plaza[];

submitParameters(): void {
    debugger;
    console.log(this.selectedPlaza);
}

HTML FILE

 <div class="pr-1">
          <div class="form-group">
            <label>Plaza</label>
            <Select type="text" class="form-control" #select (change)="valueChange($event)" [(ngModel)]="selected">
              <option [ngValue]='0' [selected]>All Plaza</option>
              <option *ngFor="let item of plazaList" [ngValue]='item.plazaCode'>{{item.plazaName}}</option>
            </Select>
          </div>
        </div>

For some reason when I log the selectedPlaza it gives me undefined. What can I try in order to resolve this?

标签: angulartypescript

解决方案


我想,我有一个解决方案,请检查下面的代码。也检查Stackblitz 链接=>

HTML:

 <select [(ngModel)] ="selected"
            name="valueCheck" 
            (change)="valueChange($event)"> 
            <option [ngValue]="undefined" disabled [selected]>Select Any </option>
            <option *ngFor="let obj of plazaList" [ngValue]="obj" > {{obj.plazaName}} </option>
 </select>

TS:

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  
  plazaList=[];
  selected:any;
  constructor(){
    for (let i = 0; i < 3; i++) {
      let temp=new Plaza();
      temp.plazaCode='pc-'+i.toString();
      temp.plazaName='p-'+i.toString();
      this.plazaList.push(temp);
    }
  }

  valueChange(event){
    console.log("selected value",event.target.value ,
    'value of selected',this.selected);
  }
}
export class Plaza{
  plazaName:string;
  plazaCode:string;
}

推荐阅读