Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular conditional validation on template driven form

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:

the template:

<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>

the component:

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...
  }
}

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?

(Note, Angular 5)

like image 628
Dallas Caley Avatar asked Feb 13 '18 22:02

Dallas Caley


People also ask

How do I validate a form in an angular form?

We can validate template-driven forms with HTML form validation attributes, which will trigger form validation directives to run. For more validation options, we can create our own validation function which is used by a validation directive. Then we can add it to our Angular module and use it in our template.

What are validation errors in angular?

Every time a form control changes, Angular runs validation and generate a list of validation errors, which results in an invalid status, or null, which results in a valid status. For example, we can add an input with validation for length and make it a required field as follows: Name is required. Name must be at least 4 characters long.

How to use conditional custom validation with formcontrolname formcontrol and ngmodel?

To use conditional custom validation with formControlName, formControl and ngModel we need to create custom validator Directive using Validator or AsyncValidator interface. Validator creates synchronous custom validator and AsyncValidator creates asynchronous custom validator. Validator and AsyncValidator has following method declarations.

How to implement template driven forms with an angular project?

To implement the Template Driven Forms with an Angular project, we first need to add a module which is essential for providing all the required components of the Template Driven Form. So, open the app.mdoule.ts and add the FormsModule imported from @angular/forms.


1 Answers

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".

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.

like image 153
Gilsdav Avatar answered Nov 14 '22 22:11

Gilsdav