Angular(2+)模板表单在<ul>中显示错误消息

时间:2017-11-07 20:49:46

标签: angular angular-forms

我今天尝试了角度形式,即使它有效,但我似乎无法使验证逻辑正确。我真正想要做的是,当一个字段不正确时,它会在表单的顶部显示一条消息,该消息在&lt;&lt;&lt;&lt;&gt;&gt;&gt;&gt;中呈现。 &LT;&#39;利&#39;&GT;标签,但仅在填写完整表格时。目前,只要关注输入框,它就会显示错误。

enter image description here

最后这是我的相关代码:

            <form #formAdd="ngForm" (ngSubmit)="submit(formAdd)">

                <!-- error reporting-->

                    <ul *ngIf="!formAdd.valid && formAdd.dirty" class="alert alert-danger">
                        <li *ngIf="className.touched && !className.valid">
                            <span *ngIf="className.errors.required">Class name is required.</span>
                            <span *ngIf="className.errors.minlength">Class name should be at least 3 characters.</span>
                        </li>
                        <li *ngIf="maxStudents.touched && !maxStudents.valid">
                            <span *ngIf="maxStudents.errors.required">Maximum number of students is required.</span>
                        </li>
                    </ul>


                <div ngModelGroup="class">
                    <div class="form-group">
                        <label for="className">Class name:</label>
                        <input required
                               minlength="3"
                               ngModel
                               #className="ngModel"
                               name="className"
                               (change)="log(className)"
                               type="text"
                               class="form-control"
                               id="className" />
                    </div>

                    <div class="form-group">
                        <label for="maxStudents">Max students:</label>
                        <input required  
                               ngModel 
                               #maxStudents="ngModel"
                               name="maxStudents" 
                               type="number" 
                               class="form-control" 
                               id="maxStudents">
                    </div>

                    <button type="submit" class="btn btn-primary" [disabled]="!formAdd.valid">Submit</button>

                </div>
            </form>

任何帮助都将非常感谢,干杯!

0 个答案:

没有答案