我的Angular 4應用程序使用生成的表單,更確切地說,使用<select>
標籤,其<option>
標籤是動態生成的,因此存在問題。在「選擇」標籤中選擇後,選擇的Angular4選項消失
我在plunker中製作了我的代碼的簡化版本。
我遇到的問題在我選擇的選項不是第一個默認值undefined
選項後立即出現:代碼值設置正確,但<option>
標籤內的文本消失。
我該如何解決這個問題?
我的Angular 4應用程序使用生成的表單,更確切地說,使用<select>
標籤,其<option>
標籤是動態生成的,因此存在問題。在「選擇」標籤中選擇後,選擇的Angular4選項消失
我在plunker中製作了我的代碼的簡化版本。
我遇到的問題在我選擇的選項不是第一個默認值undefined
選項後立即出現:代碼值設置正確,但<option>
標籤內的文本消失。
我該如何解決這個問題?
變化[ngValue]在選項[值]
<select [(ngModel)]="value">
<option [ngValue]="undefined">(undefined)</option>
<option *ngFor="let entry of getEntries()" [value]="entry.code">{{entry.label}}</option>
</select>
這將工作。
這是解決方案:
//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 {}
它與您合作嗎? – ZAhmed
你爲什麼要使用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 {}
很簡單的解決方案,工作正常,謝謝!但是你知道'ngValue'和'value'有什麼區別嗎?我是否應該將第一個[ngValue] =「undefined」'更改爲'[value] =「undefined」'? – Dartz
[ngValue]將爲該元素創建角度綁定。然而[值]是簡單的屬性綁定。我們應該只進行屬性綁定,因爲我們已經有了ngModel來訪問它的值。 – Ashvin777