简体   繁体   中英

Angular4 selected option disappears after selection in “select” tag

I have an issue in my Angular 4 application with a generated form, and more precisely, with a <select> tag where its <option> tags are dynamically generated.

I made a simplified version of my code in plunker .

The problem I'm experiencing occurs immediately after I select an option that's not the first default undefined option : the code value is set correctly but the text inside the <option> tag disappears.

How could I fix that ?

Change [ngValue] in options to [value]

<select [(ngModel)]="value">
  <option [ngValue]="undefined">(undefined)</option>
  <option *ngFor="let entry of getEntries()" [value]="entry.code">{{entry.label}}</option>
</select>

This will work.

Why are you using getEntries() function you can directly use entries array in your class App like below code

//our root app component
import {Component, NgModule, VERSION} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'my-app',
  template: `
    <h1>Hello world</h1>
    <p>Please select one option : </p>
    <select [(ngModel)]="value">
      <option [ngValue]="undefined">(undefined)</option>
      <option *ngFor="let entry of entries" [ngValue]="entry.code">{{entry.label}}</option>
    </select>
    <p>Selected value : {{value}}</p>
  `,
})
export class App {
  value = undefined;
  entries=[{code:"1", label:"abra"},{code:"2", label:"kadabra"}];
  constructor() {
  }


}

@NgModule({
  imports: [ BrowserModule, FormsModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

This is the solution :

//our root app component
import {Component, NgModule, VERSION} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'my-app',
  template: `
    <h1>Hello world</h1>
    <p>Please select one option : </p>
    <select (change) = 'myfun($event)'  [value] = 'this.value'>
      <option *ngFor="let entry of getEntries()"   [selected]= 'this.value'  (value)="entry.code"  >{{entry.label}}</option>
    </select>
    <p>Selected value : {{value}}</p>
  `,
})
export class App {
   value:string

  constructor() {
  }

  myfun(event){
   console.log(event.target.value)
   this.value = event.target.value;
  }

  getEntries() {
    const entries = [];
    entries.push({code:"1", label:"abra"});
    entries.push({code:"2", label:"kadabra"});

    return entries;
  }
}

@NgModule({
  imports: [ BrowserModule, FormsModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM