如何有条件地要求角度4中的表格输入? [英] How to conditionally require form inputs in angular 4?

查看:80
本文介绍了如何有条件地要求角度4中的表格输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用模板驱动的表单来添加任务,并且有2个类型为number的输入字段,用于估计完成任务所需的分钟数,

I am using template driven forms for adding the task, and there are 2 input fields of type number for estimated mins to complete task,

  • 一个字段用于估计小时数,
  • 另一个人需要几分钟才能完成任务

因为任务估计可以像 1hrs 这样的小时完成,也可以像 1Hrs 30Mins 这样的小时和分钟完成,所以我想设置属性 required 以有条件地输入.因此,必须设置2个输入之一,否则在提交表单时如果两个输入都为空,则会发生表单验证错误.

since the task estimate can be done either in hours like 1hrs , or in hours and minutes like 1Hrs 30Mins , so i want to set attribute required to inputs conditionally. So one of the 2 inputs must be set or form validation error will occur if both inputs are empty when submitting form.

到目前为止,我已经做到了,但是验证不起作用

so far i have done this but validation is not working

<form class="add-task" (ngSubmit)="onSubmit(newtask)" #newtask="ngForm">  
    <div class="estimate-container">
        <input 
            type="number" 
            min="0" 
            max="10" 
            id="estimate_hrs" 
            ngModel 
            name="estimate_hrs"
            mdInput 
            [required]="!estimateMins.valid" 
            placeholder="Estimated Hours" 
            #estimateHrs="ngModel"
        >
        <div class="error-msg" *ngIf="!estimateHrs.valid && !estimateMins.valid">
            Please enter estimated hours 
        </div>
        <input 
            type="number" 
            min="0" 
            max="60" 
            id="estimate_min" 
            ngModel 
            name="estimate_min" 
            mdInput 
            [required]="!estimateHrs.valid" 
            placeholder="Estimated Minutes" 
            #estimateMins="ngModel"
        >
        <div class="error-msg" *ngIf="!estimateMins.valid && !estimateHrs.valid">
            Please enter estimated minutes
        </div>   
    </div>
    <button type='submit' [disabled]="!newtask.valid" >Submit</button>
</form>

推荐答案

尝试改用[attr.required].

Try using [attr.required] instead.

   <input 
        type="number" 
        min="0" 
        max="10" 
        id="estimate_hrs" 
        ngModel 
        name="estimate_hrs"
        mdInput 
        [attr.required]="!estimateMins.valid" 
        placeholder="Estimated Hours" 
        #estimateHrs="ngModel"
    >

这篇关于如何有条件地要求角度4中的表格输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆