ZanattMan
ZanattMan

Reputation: 736

Angular 2 html form validation

I've created a form using html validations with Angular 2.

I want to to check the sate of the inputs (no empty, correct format, etc) when the user click to a certain button. At the moment I'm doing it as following:

    <form id="memberForm" #memberForm="ngForm" >
        <input
          type="text"
          id="MemberName"
          required
          name="MemberName"
          [(ngModel)]="newMember.name">        
    </form>
    <div  
        [ngClass]="{'button_disabledButton' : !memberForm?.valid}" 
        (click)="onSubmit(memberForm?.valid, memberForm);"> 
            <span>Next</span>
    </div>

With this, I'm only evaluating the input once clicked and focus out. How can I make it hapens when the user click in the "Next" element?

Upvotes: 0

Views: 134

Answers (1)

Roberc
Roberc

Reputation: 1956

You should make getter/setter solution for your ngModel input. In the .ts file in the appropriate class put this:

savedVar:string = '';
get variable(): string {
  return this.savedVar;
}
set variable(str: string) {
  this.savedVar = str;
  // do your validation
}

In template use ngModel=variable like this:

<input [(ngModel)]="variable">

Upvotes: 1

Related Questions