Home > Software engineering >  Make button to be disabled initially, and enable if length of input is 10 in Angular
Make button to be disabled initially, and enable if length of input is 10 in Angular

Time:11-07

I have a requirement where I have to keep the button to be disabled initially and enable it only when the length of my input is 10.

<div >
  <label for="MSISDN_Value" >MSISDN:</label>
  <input type="number" 
    onkeyPress="if(this.value.length === 10) return false;" 
    [(ngModel)]="MSISDN_Value" 
    id="MSISDN_Value" 
    name="MSISDN_Value"
    >
</div>
<div >
  <button  type="submit" 
    [disabled]="true">Search</button>
</div>

I tried [disabled] = "MSISDN_Value.length !== 10" but it did not work, there are many solutions that disable buttons, but I couldn't find any solution which enables buttons in Angular5.

CodePudding user response:

Hii the problem is you are checking integer value with === operator which is returning false. see my below code.

<div >
<label for="MSISDN_Value" >MSISDN:</label>
<input type="number"
#num
max=10
(change)="toggle2($event)"  
id="MSISDN_Value" 
  name="MSISDN_Value"
  >
</div>
<div >
<button  type="submit" 
  [disabled]="this.num.value==10?false:true">Search{{this.num.value===10}}</button>
</div>

//.ts file
toggle2(event){
  console.log(event.target.value)
}

CodePudding user response:

After searching, I took the help of events and used (input) function binding and fired an event on even.target.value changes to toggle [isDisabled]

<div >
    <label for="MSISDN_Value" >ISMSDN/IMEI:</label>
    <input type="number" onkeyPress="if(this.value.length === 10) return false;" (input)="onSearchChanges($event.target.value)" [(ngModel)]="MSISDN_Value" id="MSISDN_Value" name="MSISDN_Value" >
  </div>
  <div >
    <button  type="submit" [disabled]="searchDisabled">Search</button>
  </div>

component.ts file

onSearchChanges(value) {
    if(value.length === 10){
      this.searchDisabled = false;
    } else{
      this.searchDisabled = true;
    }
  }
  • Related