bigskull
bigskull

Reputation: 591

Angular 2 - unexpected behaviour on button disabled

in my app, I've a button initially disabled. If the input field is populated the button is enabled but there is a strange behavior. If disabled, the icon is forbidden and it is unclickable (this is obviously right). On digit something in the input field, the button changes class and enabled but the icon doesn't change though it is possible to click on the button (this is strange). If I click on the input field, the icon changes and the hand icon is visible instead of forbidden signal. The expected behavior is to have hand icon immediately on digit something in the input field, This is my code:

<button (click)='onClick()' [disabled]="isDisabled" [class]="checkValid()" type="submit">Search</button>

checkValid() {
   if (this.myInput != "") {
            this.isDisabled= false;
            return "btn btn-primary";
        } else {
            this.isDisabled= true;
            return "btn btn-primary disabled";
        }
    }

Any suggestion?

Upvotes: 0

Views: 164

Answers (1)

Mykola Zatonatskiy
Mykola Zatonatskiy

Reputation: 349

Here is the solution for your application:

It is better to use [ngClass] instead of just [class]. And try to avoid return state in HTML, because your method will work in a cycle.

I have added ngClass statement and added (keyup)='checkValid()' in input field.

@Component({
  selector: 'my-app',
  template: `
    <input type="text" [(ngModel)]="myInput" (keyup)='checkValid()'>
    <button (click)='onClick()' [disabled]="isDisabled" class='btn btn-primary' [ngClass]="{'disabled': isDisabled}" type="submit">Search</button>
  `,
})
export class App {
  isDisabled: boolean = true;
  myInput: string = '';

  constructor() {
  }

  checkValid() {
   if (this.myInput != "") this.isDisabled= false;
   else this.isDisabled= true;
  }

  onClick(){

  }
}

Planker:

https://plnkr.co/edit/nWQiCy2ZVuZTPSVCBr4y?p=preview

Upvotes: 2

Related Questions