Reputation: 65870
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
Upvotes: 2
Views: 15877
Reputation: 14669
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
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
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.
Upvotes: 7
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