[英]how to bind Pre-populated data from object to radio button in Angular 5
I am working on Angular 5 application. 我正在研究Angular 5应用程序。 I got radio button for Gender which value is pre-populated radio selection based on value it receving and I need to know how to use ng-if inline in html template.
我有一个用于Gender的单选按钮,该值是根据接收到的值预先填充的单选,我需要知道如何在html模板中使用ng-if inline。 GenderType: string where value 1 is for male and 2 for female.
GenderType:字符串,其中值1是男性,女性是2。
I have tried *ngIf but its not working out 我已经尝试过* ngIf但它没有解决
<div class="k-form-field">
<span>Gender</span>
<input type="radio" name="gender" id="female" class="k-radio" *ngIf:{{respondent.genderType='1'}} === checked="checked" disabled>
<label class="k-radio-label" for="female">Female</label>
<input type="radio" name="gender" id="male" class="k-radio" disabled>
<label class="k-radio-label" for="male">Male</label>
</div>
You don't need ngIf to change the value form a property. 您不需要ngIf来更改属性的值。 You can just use a block of javascript for a conditional attribute:
您可以使用一个javascript块作为条件属性:
<input
type="radio"
name="gender"
id="female"
[attr.checked]="respondent.genderType=='1' ? 'checked' : null" />
Another option is to use forms in an "Angular way", either with ngModel or with Reactive Forms . 另一种选择是通过ngModel或Reactive Forms以“角度方式”使用表单 。
Assuming genderType 1 is female and 2 is male, you only has to bind that in the checked attribute. 假设性别类型1是女性,性别类型2是男性,则只需将其绑定到选中的属性中。 You don't need the ngIf.
您不需要ngIf。 NgIf is to display or hide a html element.
NgIf是显示或隐藏html元素。 Try with this (also I removed the disabled attribute):
试试这个(我也删除了disable属性):
<div class="k-form-field">
<span>Gender</span>
<input type="radio" name="gender" id="female" class="k-radio" [attr.checked]="respondent.genderType === '1' ? 'checked' : null">
<label class="k-radio-label" for="female">Female</label>
<input type="radio" name="gender" id="male" class="k-radio" [attr.checked]="respondent.genderType === '2' ? 'checked' : null">
<label class="k-radio-label" for="male">Male</label>
</div>
final answer that works for me 对我有用的最终答案
<div class="k-form-field">
<span>Gender</span>
<input type="radio" name="gender" id="female" class="k-radio" [attr.checked] ="respondent.genderType=='2' ? 'checked' : null" disabled>
<label class="k-radio-label" for="female">Female</label>
<input type="radio" name="gender" id="male" class="k-radio" [attr.checked] ="respondent.genderType=='1' ? 'checked' : null" disabled>
<label class="k-radio-label" for="male">Male</label>
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.