模板驱动表单上的角度条件验证

时间:2018-02-13 22:58:05

标签: angular validation

我有一个输入字段,只有在设置了另一个值时才需要输入字段。另一个值来自select。请注意,我的实际形式要复杂得多,但这里有一个示例,显示与此问题相关的部分:

模板:

<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。实现这个的最简单方法是什么?

(注意,Angular 5)

1 个答案:

答案 0 :(得分:5)

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

你有[ngClass] =“{'has-error':f.submitted&amp;&amp;!orderNumber.valid}”的问题,因为在“ngAfterViewChecked”期间会设置有效,所以Angular不想让再次工作。 用[class.has-error]="f.submitted && !orderNumber.valid"代替它不会再让它哭了。