在“select”标签中选择后,Angular4选择选项会消失

时间:2017-08-10 09:44:17

标签: javascript angular html-select angular-forms

我的Angular 4应用程序中存在生成表单的问题,更确切地说,我的<select>标记是动态生成的<option>标记。

我在plunker中制作了我的代码的简化版本。

我选择的选项不是第一个默认undefined选项后,我遇到的问题就出现了:代码值设置正确但<option>标签内的文字消失了。

我怎么能解决这个问题?

2 个答案:

答案 0 :(得分:1)

为什么使用getEntries()功能,您可以在entries代码中直接使用class App数组

//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 {}

答案 1 :(得分:0)

这是解决方案:

//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 {}