I would like to make these inputs to display a message such as "Name is required" when submitted(so the submit button is disabled until there is name inside). Is there perhaps a simple way to do it with Angular 2 Template Driven forms? I guess that I should provide some properties in form's HTML, and connect it to a component, but could not figure it out while following the samples in documentation. Appreciate all the help.
<form class="">
<div>
<p>Name:</p>
<input type="text">
</div>
<div class="link-input">
<p>City:</p>
<input type="text">
</div>
<button
(click)="submitForm()">
Submit
</button>
</form>
I also having this question and i found answer and that i wanted to share with you. I created a login form with validation which is look like as following:
<div class="col-md-6 col-md-offset-3">
<h2>Login</h2>
<form name="form" (ngSubmit)="f.form.valid && login()" #f="ngForm" novalidate>
<div class="form-group" [ngClass]="{ 'has-error': f.submitted && !username.valid }">
<label for="username">Username</label>
<input type="text" class="form-control" name="username" [(ngModel)]="model.username" #username="ngModel" required />
<div *ngIf="f.submitted && !username.valid" class="help-block">Username is required</div>
</div>
<div class="form-group" [ngClass]="{ 'has-error': f.submitted && !password.valid }">
<label for="password">Password</label>
<input type="password" class="form-control" name="password" [(ngModel)]="model.password" #password="ngModel" required />
<div *ngIf="f.submitted && !password.valid" class="help-block">Password is required</div>
</div>
<div class="form-group">
<button [disabled]="loading" class="btn btn-primary">Login</button>
<img *ngIf="loading" src="loading.gif" />
<a [routerLink]="['/register']" class="btn btn-link">Register</a>
</div>
</form>
</div>
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { AlertService, AuthenticationService } from '../services';
@Component({
templateUrl: './login.component.html'
})
export class LoginComponent implements OnInit {
model: any = {};
loading = false;
returnUrl: string;
constructor(
private route: ActivatedRoute,
private router: Router,
private authenticationService: AuthenticationService,
private alertService: AlertService) { }
ngOnInit() {}
login() {
this.loading = true;
this.authenticationService.login(this.model.username, this.model.password)
.subscribe(
data => {
this.router.navigate([this.returnUrl]);
},
error => {
this.alertService.error(error);
this.loading = false;
});
}
}
I hope this will help you if you need any help you can write me. I feel happy to help you. @Smithy i am also learning angular 2.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With