我正在尝试默认选择角度为4的单选按钮。
以下是我的模板代码:
<div class="form-check form-check-inline">
<label class="form-check-label"> </label>
<input type="radio" class="form-check-input"
name="type"
[(ngModel)]="searchForm.type"
[value]="['all']"
[checked]='searchForm.type ==='all''
> All
</div>
我正在我的组件ngOnInit
中初始化默认值export class myComponent{
searchForm:FormVO = new FormVO();
ngOnInit(){
this.searchForm.type='all';
}
}
我也尝试过构造函数初始化,这里实际上值是以构造函数或者nginit方式设置为searchForm.type。 我面临的问题是我无法仅在模板中选择收音机。
这些是我尝试的方式:
方式1:
[checked]="searchForm.type ==='all'"
方式2:
[checked]="searchForm.type ==='all' ? true : false"
方式3:
[checked]="searchForm.type =='all'"
我也读过很少的数字,我可以默认选中。我没有尝试这种方式,因为我只希望解决方案包含字符串值。
提前致谢。
我请求避免将此标记为重复问题,因为我已经尝试了所有这些问题的解决方案,但没有任何效果。
我正在使用角度为4的角度cli。
答案 0 :(得分:1)
我通过在输入框周围添加表单标记解决了这个问题。请试一试,看看它是否适合你。
答案 1 :(得分:0)
文档有一个很好的例子,说明如何使用Angular
https://angular.io/api/forms/RadioControlValueAccessor#how-to-use-radio-buttons-with-form-directives
import {Component} from '@angular/core'; @Component({ selector: 'example-app', template: ` <form #f="ngForm"> <input type="radio" value="beef" name="food" [(ngModel)]="myFood"> Beef <input type="radio" value="lamb" name="food" [(ngModel)]="myFood"> Lamb <input type="radio" value="fish" name="food" [(ngModel)]="myFood"> Fish </form> <p>Form value: {{ f.value | json }}</p> <!-- {food: 'lamb' } --> <p>myFood value: {{ myFood }}</p> <!-- 'lamb' --> `, }) export class RadioButtonComp { myFood = 'lamb'; }
将选择与分配给value="..."
的值匹配的myFood
的值(示例中为'lamb'
)。