[英]Angular5 [Select+Option]: how to use complex data?
由於某些原因,我在app.component.ts文件中有一個復雜的數據:
export class AppComponentimplements OnInit {
tests = {
'name': 'Bob',
'grade': '5th',
'score': [
['math', 'A', 'A+', 'A-'],
['english', 'B', 'B-', 'A'],
['french', 'A', 'A+', 'A'],
['chem', 'C', 'C', 'C'],
['sport', 'B', 'B', 'B']
]};
}
我想將“得分”下的第一項顯示到選擇/選項下拉按鈕中。
(這些是:['數學','英語','法語','化學','運動'])
在app.component.html文件中,以下代碼是我的多次嘗試之一。 但是可悲的是它不起作用。
<select>
<option *ngFor="let test of tests" [ngValue]="test.score[0]">
{{test.score[0]}}
</option>
</select>
我該怎么做呢?
您的HTML代碼錯誤。
嘗試這個。
<select>
<option *ngFor="let score of tests.score" [ngValue]="tests.score[0]" >
{{score[0]}}
</option>
</select>
正確的方法,您應該可以獲取選定的值 :
<select id='subjects' [formControl]="selectedSubject">
<option *ngFor="let test of tests.score" [ngValue]="test[0]">
{{test[0]}}
</option>
</select>
作為[ngValue] ,如果要獲取選定的完整數組,可以使用test
: ['math', 'A', 'A+', 'A-']
:
<option *ngFor="let test of tests.score" [ngValue]="test">
{{test[0]}}
</option>
或test[0]
,是否要選擇數組的第一個值(例如math
):
<option *ngFor="let test of tests.score" [ngValue]="test[0]">
{{test[0]}}
</option>
也不要記得在AppModule中包含ReactiveFormsModule
。 如果我們想使用Reactive Forms (formControl / formGroup指令...),如代碼示例所示
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.