<div class="form-group">
<div class="input-group input-group-primary">
<label for="name" class="input-group-addon">Username</label>
- <input id="name" type="text" class="form-control" placeholder="Enter your username" [formControl]="name">
+ <input id="name" type="text" class="form-control" placeholder="Enter your username" [formControl]="usernameForm">
+ </div>
+ <div *ngIf="usernameForm.invalid && (usernameForm.dirty || usernameForm.touched)"
+ class="alert alert-danger">
+
+ <div *ngIf="usernameForm.errors?.['required']">
+ Name is required.
+ </div>
</div>
</div>
- <button type="submit" class="btn btn-primary" (click)="updateName()">Pick Name</button>
+ <button type="submit" class="btn btn-primary" (click)="updateName()" [disabled]="usernameForm.invalid">Pick Name</button>
</div>
</div>
-<p>Value: {{ name.value }}</p>
+<p>Value: {{ usernameForm.value }}</p>
+<p>Form Status: {{ usernameForm.status }}</p>
import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';
+import { Validators } from '@angular/forms';
import { Router } from "@angular/router";
import { UserService } from "../user.service";
})
export class UserComponent {
- name = new FormControl('');
+ usernameForm = new FormControl('', Validators.required);
updateName(): void {
- var input = this.name.getRawValue();
+ var input = this.usernameForm.getRawValue();
if (input !== null) {
this.userService.setUser(input);
this.router.navigate(['chatrooms'])