2017-08-10 35 views
0

私のAngular 4アプリケーションでは、生成されたフォームで、より正確には<select>タグの<option>タグが動的に生成されます。「選択」タグで選択した後、Angular4選択されたオプションが消える

私はplunkerに私のコードの簡易版を作りました。

最初のデフォルトundefinedオプションではないオプションを選択した直後に問題が発生します。コード値は正しく設定されていますが、<option>タグ内のテキストは消えます。

私はそれを修正することができますか?

答えて

2

変更は、[ngValue] [値]のオプションで

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

これは動作します。

+0

非常に簡単な解決策でentries配列を使用することができますgetEntries()機能を使用しています!しかし、 'ngValue'と' value'の違いは何ですか?私は最初の '[ngValue] = "未定義"' 'に[値]あまりに' = "未定義" を変更する必要がありますか? – Dartz

+2

[ngValue]は、その要素のAngularバインディングを作成します。ただし、[値]は単純な属性バインディングです。属性バインディングは、すでに値にアクセスするためにngModelを使用できるため、行う必要があります。 – Ashvin777

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 {} 
+0

あなたと一緒でしたか? – ZAhmed

1

は、なぜあなたは、おかげであなたが直接、正常に動作し、あなたの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 {} 

コード以下のよう
関連する問題