模板驱动形式的角度条件验证 [英] Angular conditional validation on template driven form

查看:115
本文介绍了模板驱动形式的角度条件验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个输入字段,仅当设置了另一个值时才需要.另一个值来自选择.注意,我的实际形式要复杂得多,但是下面的示例显示了与此问题相关的部分:

I have an input field that is required only if another value is set. The other value is from a select. Note, my actual form is much more complicated but here is an example showing the parts that are pertinent to this question:

模板:

<form name="createPaymentForm" (ngSubmit)="f.form.valid && createPayment()" #f="ngForm" novalidate>

  <select name="orderNumberType" #orderNumberType="ngModel" 
    [(ngModel)]="payment.orderNumberType">
    <option [ngValue]="undefined" disabled>Select</option>
    <option *ngFor="let opt of paymentIdOptions" [value]="opt.id">{{opt.label}}</option>
  </select>

  <div [ngClass]="{ 'has-error': f.submitted && !orderNumber.valid }">
    <input type="text" name="orderNumber"
      [(ngModel)]="payment.orderNumber" #orderNumber="ngModel">
  </div>

</form>

组件:

import { Component, OnInit } from '@angular/core';
import { PaymentsService } from '../../../services/payments.service';
import { Payment } from '../../../models';

@Component({
  selector: 'app-new-payment',
  templateUrl: './new-payment.component.html',
  styleUrls: ['./new-payment.component.scss']
})
export class NewPaymentComponent implements OnInit {
  paymentIdOptions: any = [];
  payment: Payment = {};

  constructor( private paymentsService: PaymentsService ) { }

  ngOnInit() {
    this.paymentsService.getOrderNumberTypes().subscribe(orderNumberTypes => {
      this.paymentIdOptions = orderNumberTypes;
    });
  }

  createPayment() {
    console.log(this.payment);
    //do something...
  }
}

我的目标是仅在orderNumberType设置为除"undefined"以外的任何其他值时才需要orderNumber.实现此目的最简单的方法是什么?

My goal is to only require the orderNumber if the orderNumberType is set to any value other than 'undefined'. What is the easiest way to implement this?

(请注意,角度5)

推荐答案

可以使用必需的Angular指令(例如[required]="payment.orderNumberType")来完成此操作(在这里,他会检查payment.orderNumberType是否未定义,null,0 ,错误或空字符串). 这是[attr.required]="payment.orderNumberType ? true : undefined"的简写.

It can be done using required Angular directive like [required]="payment.orderNumberType" (here he check if payment.orderNumberType is undefined, null, 0, false or empty string). This is a shorthand for [attr.required]="payment.orderNumberType ? true : undefined".

您对[ngClass] ="{'has-error':f.submitted&!orderNumber.valid}"有疑问,因为有效期将在"ngAfterViewChecked"期间设置,因此Angular不想使再次工作. 用[class.has-error]="f.submitted && !orderNumber.valid"替换它不会使其再哭了.

You have problem with [ngClass]="{ 'has-error': f.submitted && !orderNumber.valid }" because valid will be set during "ngAfterViewChecked" so Angular don't want to make the job again. Replacing it by [class.has-error]="f.submitted && !orderNumber.valid" will not make it cry anymore.

这篇关于模板驱动形式的角度条件验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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