Sampath
Sampath

Reputation: 65870

Angular 2 [disabled] is not working

I need to disable the Add Hero button when there is nothing on the text box.Can you tell me why this is not working ?

<form novalidate #f="ngForm">

<ul>
  <li *ngFor="let hero of heroes">{{hero.name}}</li>
</ul>

<label>New hero name: <input required #newHeroName /></label>
<button (click)="addHero(newHeroName.value); newHeroName.value=''" 
         [disabled]="f.invalid">Add Hero</button>

</form>

Plunker is here : Plunker

The file is this : app/toh/hero-list.component.html

enter image description here

Upvotes: 2

Views: 15877

Answers (4)

Just change your code as below, it works with your plunker:

<label>New hero name: <input [ngModel]="newHeroName.value" #newHeroName required name="heroname"/></label>
<button (click)="addHero(newHeroName.value); newHeroName.value=''" 
     [disabled]="!f.form.valid">Add Hero</button>

Upvotes: 0

SeleM
SeleM

Reputation: 9638

To be more viewed; here's @GünterZöchbauer Solution since the plnkr cannot be edited :

just change those parts as follows:

<label>New hero name: 
<input #newHeroName required (input)="null" /> </label> 
<button (click)="addHero(newHeroName.value); newHeroName.value=''" 
 [disabled]="!newHeroName.value">Add Hero</button>

PLEASE CHECK @GünterZöchbauer's ANSWER

Upvotes: 3

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657238

If you add (input)="null" like

<input #newHeroName required (input)="null"

then Angular will run change detection after every input event.

Without it Angular won't recognize any change.

With

<button [disabled]="!newHeroName.value">Add Hero</button>

you get the buttons enable/disable set depending on the input being empty or not.

Plunker example

enter image description here

Upvotes: 7

Karl
Karl

Reputation: 3099

Change your input to this, then it works:

...
<input #newHeroName type="text" 
class="form-control" 
id="name" required [(ngModel)]="model" name="name" ></label>
...

Upvotes: 0

Related Questions