【问题标题】:Disable button while ngForm is invalidngForm 无效时禁用按钮
【发布时间】:2017-08-24 08:04:25
【问题描述】:

我有一个添加模式,我需要禁用“保存”按钮,直到内容被填满。随着内容的填充,按钮应该被启用。这是我的代码

<div bsModal #editModal="bs-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
<div class="modal-dialog modal-md">
    <div class="modal-content">
        <form name='groupForm' #groupForm="ngForm" novalidate>
            <div class="modal-header">
                <h4 class="modal-title wd-title-popup">Add Access Group</h4>
            </div>
            <div class="modal-body row">
                <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 accssContent paddingLeftClass">
                    <md-input-container style='width: 100%;margin-bottom: 6px !important;'>
                        <input type="textbox" mdInput name="admin" [(ngModel)]="group.groupName" placeholder="Access Group Name" required>
                    </md-input-container>
                </div>
            </div>
            <div md-theme="reports" class="modal-footer" style="text-align: center;">
                <div layout-align="end center" layout="row">
                    <button md-raised-button class="md-raised color-white" (click)="editModal.hide()" style="width: 45%;margin: 10px 5px;background-color: #FF5252;">Cancel</button>
                    <button md-raised-button class="md-raised color-white" [disabled]="!groupForm.form.valid" (click)="accessGroup(group)" style="width: 45%;margin: 10px 5px;background-color:#58B6A2;">Save</button>
                </div>
            </div>
        </form>
    </div>
</div>

这同样适用于其他按钮。我在这里做错了什么?

【问题讨论】:

  • 添加到表单[formGroup]="myForm",然后禁用[disabled]="!myForm.valid"。表单中还有novalidate 属性,用于禁用浏览器的本机表单验证。
  • 我删除了 [disabled] 中的表单,但它不起作用。

标签: angular angular2-forms


【解决方案1】:

尝试使用invalid 属性。改成这样:

<button md-raised-button class="md-raised color-white"  
        (click)="accessGroup(group)" 
        [disabled]="groupForm.invalid">Save</button>

链接到Plunker Demo

【讨论】:

    【解决方案2】:

    您的表单有novalidate,这可能会导致表单跳过验证并且未设置有效变量

    【讨论】:

    • Notice that now the single input is in a form element. The novalidate attribute in the &lt;form&gt; element prevents the browser from attempting native HTML validations. 在这里阅读:angular.io/guide/reactive-forms
    猜你喜欢
    • 2016-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-08
    • 2013-02-24
    • 1970-01-01
    • 2020-04-05
    • 1970-01-01
    相关资源
    最近更新 更多