Reputation: 36299
I have this very basic form, that I am trying to enable/disable a button on if the form is/isn't filled out. When using this form, the button is always enabled even when I add/remove data in the input fields.
<form #activationForm="ngForm">
<input type="email" ([ngModel])="email" placeholder="{{'activation.email' | translate}}" required>
<input type="text" ([ngModel])="code" placeholder="{{'activation.code' | translate}}" required>
<button [disabled]="activationForm.form.invalid" class="button button--success" translate="activation.activate" (click)="activate()"></button>
</form>
@Component({
selector: 'app-activation',
templateUrl: './activation.component.html',
styleUrls: ['./activation.component.scss']
})
export class ActivationComponent {
public email: string = '';
public code: string = '';
}
Why is the button always enabled?
Upvotes: 1
Views: 363
Reputation: 12900
I would suggest using Reactive Forms. There's a cleaner way to do what you want.
Here's an example:
App Module:
import { ReactiveFormsModule } from '@angular/forms';
imports: [
...
ReactiveFormsModule
]
Component TypeScript:
this.activationForm = new FormGroup({
email: new FormControl('', [Validators.required, Validators.email]),
code: new FormControl('', [Validators.required])
});
Component Template:
<form [formGroup]="activationForm" (ngSubmit)="onSubmit($event)">
<input formControlName="email" />
<input formControlName="code" />
<button [disabled]="activationForm.invalid">Submit</button>
</form>
If you're using Angular Material, you can then leverage mat-hint
or mat-error
to assist with validation messages/hints. You can also make your own, of course.
The bonus with Reactive Forms is that everything is accessible. For example, you can do 'dynamic stuff' with your form by accessing their FormControl
with this.activationForm.get('email')
. The same goes for the form itself (ex: this.activationForm.setValue(...)
). It's pretty powerful and in my opinion, much more preferable than NgForm.
Upvotes: 3
Reputation: 24414
to set two way data binding with ngModel it like this [(ngModel)]="email"
also you have to provide name attribute
<form #activationForm="ngForm">
<input type="email" name="email" [(ngModel)]="email" placeholder="{{'activation.email' }}" required>
<input type="text" name="code" [(ngModel)]="code" placeholder="{{'activation.code' }}" required>
<button [disabled]="activationForm.form.invalid" class="button button--success" translate="activation.form.invalid" (click)="activate()">create</button>
</form>
Upvotes: 2