[英]select default option value from angular typescript array
I have an array of data in my typescript file我的打字稿文件中有一组数据
app.component.ts
data = [{id:1, name: "book1"}, {id:2, name:"book2"}, {id:3, name: "book3"}]
My html page:我的html页面:
app.component.html
<select id="category" class="form-control">
<option *ngFor="let d of data; let i = index;" [selected]="i == 0" [value]="d.id">{{d.name}}</option>
</select>
I want to select book1
for my default value.我想选择
book1
作为我的默认值。 But It select nothing.但它什么都不选。 How can I solve this problem ?
我怎么解决这个问题 ? I'm using
angular 7.1.3
.我正在使用
angular 7.1.3
。
using ng-selected
in the option
tag should work在
option
标签中使用ng-selected
应该可以工作
https://www.w3schools.com/angular/ng_ng-selected.asp https://www.w3schools.com/angular/ng_ng-selected.asp
You need to bind the value to the id of the selected item.您需要将该值绑定到所选项目的 id。
HTML HTML
<mat-form-field>
<mat-select [(value)]="selected">
<mat-option>None</mat-option>
<mat-option value="option1">Option 1</mat-option>
<mat-option value="option2">Option 2</mat-option>
<mat-option value="option3">Option 3</mat-option>
</mat-select>
</mat-form-field>
TS TS
selected = 1;
For furthemor information just check the official guide of angular forms有关更多信息,请查看角形式的官方指南
I am giving the solution for Template driven approach
with simple array
iterated with *ngFor
for your DropDown我正在为
Template driven approach
提供解决方案,其中simple array
使用*ngFor
为 DropDown 迭代的simple array
Working Stackbliz Demo 工作 Stackbliz 演示
HTML: HTML:
<div>
<label>Dropdown with default option loaded Template Driven: </label
><br /><br />
<select
id="country"
name="country"
[ngModel]="selectedValue"
#subscription="ngModel"
>
<option
*ngFor="let country of countryArray;let i = index"
[value]="country"
>{{i}}{{country}}</option
></select
>
</div>
TypeScript:打字稿:
export class AppComponent implements OnInit{
countryArray = ["USA", "India", "Philippines","UK"];
selectedValue ;
onSubmit(form: NgForm){
console.log("submit button clicked");
}
ngOnInit() {
this.selectedValue = this.countryArray[1];
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.