gpt4 book ai didi

angular - 在 Angular Material 2 的 md-select 中设置默认选项

转载 作者:行者123 更新时间:2023-12-02 08:13:41 27 4
gpt4 key购买 nike

我试图在 angular-material2 的 md-select 中设置默认选项,但无济于事。

form2.component.ts:

export class Form2Component implements OnInit {
frequency = [
{"title" : "One Time", "description" : "", "discount" : {"value" : 0, "type" : "value"} },
{"title" : "Weekly", "description" : "", "discount" : {"value" : 20, "type" : "percent"} },
{"title" : "Every other Week", "description" : "", "discount" : {"value" : 15, "type" : "percent"} },
{"title" : "Monthly", "description" : "", "discount" : {"value" : 10, "type" : "percent"} }
]
constructor(){}
ngOnInit(){}
}

form2.component.html:

<md-select placeholder="Frequency" [formControl]="userForm.controls['frequency']">
<md-option *ngFor="let frequ of frequency" [value]="frequ" [selected]="frequ.title == 'Weekly'">{{frequ?.title}}</md-option>
</md-select>

最佳答案

由于您使用的是响应式表单,因此可以将默认值设置为表单控件。所以你可以从数组中找到你想要的 frequency 并将其设置为默认值,如:

this.userForm = this.fb.group({
frequency: this.frequency.find(x => x.title == 'Weekly')
})

并从模板中删除selected:

<form [formGroup]="userForm">
<md-select placeholder = "Frequency" formControlName="frequency" >
<md-option *ngFor="let frequ of frequency" [value]="frequ" > {{frequ?.title}} </md-option>
</md-select>
<form>

Demo

关于angular - 在 Angular Material 2 的 md-select 中设置默认选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43884322/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com