我正在构建一个用户界面,用户可以在其中创建两种类型的内容,即LINK和MESSAGE。
我会使用内置解决方案,例如Ionic中的Segment组件,但由于设计要求,这是不可能的。
我正在做的是我有两个无线电输入
<input [(ngModel)]="notificationCreateType" type="radio" id="notification_type_link" name="notificationType" value="0" class="custom-radio" />
<input [(ngModel)]="notificationCreateType" checked type="radio" id="notification_type_message" name="notificationType" value="1" class="custom-radio" />
值0表示链接,值1表示消息。
<div *ngIf="notificationCreateType == '0'">
... stuffs here
</div>
<div *ngIf="notificationCreateType == '1'">
... stuffs here
</div>
当选择任何一个单选选项时,它似乎工作正常,但当页面加载且已选中单选选项时最初不起作用。
[(ngModel)]="notificationCreateType"
肯定会使用无线电输入的值,并将notificationCreateType
设置为该值,尽管当已经通过设置checked
属性检查输入时,它不会这样做
我想做的是让ngModel
尊重输入的checked
属性,或者更好的是,我可以在组件的ts文件中设置notificationCreateType
的初始值,该文件用于在模板中自动检查无线电输入。
这可能吗,因为我浏览了许多文档,包括官方的Ionic和Angular文档,仍然没有发现关于Radio输入的详细信息。
从模板中删除checked
属性。这是无用的,因为Angular会用notificationCreateType
的起始值覆盖检查的值。所以你只需要
<input [(ngModel)]="notificationCreateType" type="radio"
name="notificationType" value="0"/>
<input [(ngModel)]="notificationCreateType" type="radio"
name="notificationType" value="1"/>
然后在组件类中,只需设置起始值:
public notificationCreateType = '1';
Angular将负责为您检查默认单选按钮。