【问题标题】:Using `ngModel` in conjunction with radio input to display or hide a section结合使用 `ngModel` 和单选输入来显示或隐藏一个部分
【发布时间】:2018-04-24 18:16:08
【问题描述】:

我正在构建一个用户界面,用户可以在其中创建两种类型的内容,即 LINKMESSAGE

我会使用内置解决方案,例如 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>

It seems to be working fine when either of the radio options are selected, but doesn't work initially when the page loads and an radio option is already checked.

[(ngModel)]="notificationCreateType" 肯定会使用无线电输入的值并将notificationCreateType 设置为它,但当已通过设置checked 属性检查输入时它不会这样做

我想做的是让ngModel 尊重输入的checked 属性,或者更好的是我可以在组件的ts 文件中设置notificationCreateType 的初始值,该文件用于检查收音机在模板中自动输入。

这是否可能,因为我浏览了许多文档,包括官方的 Ionic 和 Angular 文档,仍然没有找到关于 Radio 输入的详细信息。

【问题讨论】:

    标签: angular ionic-framework radio-button


    【解决方案1】:

    从模板中删除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 会为你检查默认的单选按钮。

    【讨论】:

    • 哇!这简直太棒了。我排除了public 关键字并且仍然有效,我希望这不会在将来造成任何问题。谢谢!
    • public 是假定的,除非指定了private,所以我认为它不会引起问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多