uksz
uksz

Reputation: 18719

Angular2 and disabling button exception

In my code I have button, that is disabled whenever the form is invalid, or not dirty.

I have:

<button type="submit" [disabled]="!myForm.valid || myForm.dirty" class="save-button">Save</button>

Which throws me

EXCEPTION: Expression '!myForm.valid || myForm.dirty) in MyFromComponent@58:38' has changed after it was checked. Previous value: 'true'. Current value: 'false' in [!myForm.valid || myForm.dirty in MyFromComponent@58:38]

Whenever the validity/dirty changes.

Any ideas?

UPDATE

It works when I enable production mode:

enableProdMode()

Upvotes: 3

Views: 1257

Answers (2)

estin sunny koothoor
estin sunny koothoor

Reputation: 201

This is contact form example, please check this.

HTML file

<form (ngSubmit)="contactSubmit()" #contactForm="ngForm">
    <div class="form-group">
        <label for="exampleInputEmail1">Name</label>
        <input type="text" class="form-control" placeholder="Name" required ngControl="name"  #name="ngForm" [(ngModel)]="cForm.name">
    </div>
    <div class="form-group">
        <label for="exampleInputEmail1">Email address</label>
        <input type="email" class="form-control" placeholder="Email" required ngControl="email"  #email="ngForm" [(ngModel)]="cForm.email">
    </div>
    <div class="form-group">
        <label for="exampleInputEmail1">Message</label>
        <textarea class="form-control" placeholder="Message" required  ngControl="message" #message="ngForm" [(ngModel)]="cForm.message" ></textarea>
    </div>
    <button type="submit" class="btn btn-default" [disabled]="!contactForm.form.valid">Submit</button>
    <button type="button" class="btn btn-default" (click)="newcForm()" >New Form</button>
</form>

TS file

import {Component} from 'angular2/core';
import {NgForm}    from 'angular2/common';

@Component({
  selector: 'my-app',
  providers: [],
  templateUrl: 'contact-us.component.html',
  directives: []
})
export class App {
   public cForm = new contactForm('','','');
    submitted = false;
    active = true;

    contactSubmit(){
        this.submitted = true;
    }
    newcForm(){
        this.cForm = new contactForm('','','');
        this.active = false;
        setTimeout(()=> this.active=true, 0);        
    }
}

export class contactForm {
    constructor(
        public name: number,
        public email: string,
        public message: string
    ) {  }
}

Click here for plunker example

Upvotes: 1

micronyks
micronyks

Reputation: 55443

I think this will serve the purpose as well.

[disabled]="!myForm.valid || !myForm.dirty"

Upvotes: 4

Related Questions