简体   繁体   中英

Conditional validations in angular2

I want to use same template for guest and customer registration forms but validations may varies as follows

Let us assume it is a Register form for Guests - firstName is required

<form #f="ngForm" novalidate (ngSubmit)="save()">
                <label>First Name:</label>
                <input type="text" name="firstName" [(ngModel)]="values.FirstName" required #firstName="ngModel">
                <div *ngIf="firstName.hasError('required') && (!firstName.pristine && !f.submitted)" class="text-danger">You must include a first name.</div>
</form>

And this is for Customer - firstName is optional

<form #f="ngForm" novalidate (ngSubmit)="save()">
                    <label>First Name:</label>
                    <input type="text" name="firstName" [(ngModel)]="values.FirstName" #firstName="ngModel">

</form>

I want to use same/onlyone template for both forms but validations varies! how could i achieve it. TIA!

NOTE: by using reactive forms I could achieve it, but knowingly I want to achieve in Template-Driven forms.

Based on this topic you can try

<input name="first" ngModel [required]="isRequired">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM