Adding nested objects to a constant in Angular2 - mongodb

Looking to understand why this isn't working as intended and possible ways to fix. I run this function and try to get it to return information filled out on a registration form to later attach to my data model. I am trying on the first entry to also put in default values so they do not stay empty as I am using MongoDB to store the data. The data model can see everything but "objects".
register.component.ts
import { Component, OnInit } from '#angular/core';
import { ValidateService } from '../../services/validate.service';
import { FlashMessagesService } from 'angular2-flash-messages';
import { AuthService } from '../../services/auth.service';
import { Router } from '#angular/router';
#Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.css']
})
export class RegisterComponent{
name: String;
email: String;
phonenumber: String;
username: String;
password: String;
objects: Object;
object1: Object;
object2: Object;
foo: String;
bar: String;
constructor(private validateService: ValidateService,
private flashMessage: FlashMessagesService,
private authService: AuthService,
private router: Router) { }
onRegisterSubmit(){
const user = {
name: this.name,
email: this.email,
phonenumber: this.phonenumber,
username: this.username,
password: this.password,
objects: {
object1: {
foo: "no foo",
bar: "no bar"
},
object2: {
foo: "no foo",
bar: "no bar"
}
}
}
this.authService.registerUser(user).subscribe(data => {
if(data.success){
this.flashMessage.show('You are now registered and can log in', {cssClass: 'alert-success', timeout: 3000});
this.router.navigate(['/login']);
} else {
this.flashMessage.show('Something went wrong', {cssClass: 'alert-danger', timeout: 3000});
this.router.navigate(['/register']);
}
});
}
register.component.html
<h2 class="page-header">Register</h2>
<form (submit)="onRegisterSubmit()">
<div class="form-group">
<label>Name</label>
<input type="text" [(ngModel)]="name" name="name" class="form-control">
</div>
<div class="form-group">
<label>Username</label>
<input type="text" [(ngModel)]="username" name="username" class="form-control">
</div>
<div class="form-group">
<label>Email</label>
<input type="text" [(ngModel)]="email" name="email" class="form-control" >
</div>
<div class="form-group">
<label>Phonenumber</label>
<input type="text" [(ngModel)]="phonenumber" name="phonenumber" class="form-control" >
</div>
<div class="form-group">
<label>Password</label>
<input type="password" [(ngModel)]="password" name="password" class="form-control">
</div>
<input type="submit" class="btn btn-primary" value="Submit">
</form>

Related

Angular model driven form click on any button will execute the submit

When i click on any button inside a form, all functions registered inside the form would be executed.
item.components.ts
import { Component, OnInit } from '#angular/core';
import { ItemsService } from '../../share/items.service';
import { MatDialogRef } from '#angular/material';
import { Item } from 'src/app/model/item';
#Component({
selector: 'app-item',
templateUrl: './item.component.html',
styleUrls: ['./item.component.scss']
})
export class ItemComponent implements OnInit {
constructor(public service:ItemsService,
public dialogRef: MatDialogRef<ItemComponent>) { }
ngOnInit() { }
onSubmit(model: Item, isValid: boolean){
console.log('!!! submit !!!');
}
addProperty(){
console.log('!!! add prop !!!');
}
onClear(){
console.log('!!! clear !!!');
}
onClose(){
console.log('!!! close !!!');
}
}
item.ts
export interface Item {
id: BigInteger | null
artNr: string;
name: string;
parentGroup: string;
childGroup: string;
properties: Array<{key: string, text: string}>;
}
items.service.ts
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse} from '#angular/common/http';
import { Observable, from } from 'rxjs';
import { FormGroup, FormControl, Validators, FormBuilder, FormGroupDirective, FormArray } from '#angular/forms'
import { Address } from '../model/address';
import { Item } from '../model/item';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'my-auth-token'
})
};
interface ResponseItem{
results:Item[];
}
#Injectable({
providedIn: 'root'
})
export class ItemsService {
constructor(private http:HttpClient, private formBuilder:FormBuilder) { }
ngOnInit(){
this.initializeItemFormGroup();
}
//** ITEM AREA */
itemForm: FormGroup;
initializeItemFormGroup(){
this.itemForm = this.formBuilder.group({
id: [null],
artNr: ['', [Validators.required]],
name: ['', [Validators.required]],
parentGroup: ['', [Validators.required]],
childGroup: [''],
properties: this.formBuilder.array([this.addPropertyGroup()] )
});
}
addPropertyGroup(){
return this.formBuilder.group({
key: [''],
text: ['']
})
}
removeProperty(index){
this.property.removeAt(index);
}
addProperty() {
this.property.push(this.addPropertyGroup());
}
get property():FormArray {
return <FormArray>this.itemForm.get('properties');
}
}
item.component.html
<form [formGroup]="service.itemForm" class="normal-form" (ngSubmit)="onSubmit(service.itemForm.value, service.itemForm.valid)">
<mat-grid-list cols="2">
<mat-grid-tile>
<div class="controles-container">
<input type="hidden" formControlName="id" >
<mat-form-field>
<input formControlName="artNr" matInput placeholder="EA0123" >
<mat-error>Artikelnummer zwingend erforderlich</mat-error>
</mat-form-field>
<mat-form-field>
<input formControlName="name" matInput placeholder="Artikelbezeichnung" >
<mat-error>Bezeichnung ist erforderlich</mat-error>
</mat-form-field>
<mat-form-field>
<input formControlName="parentGroup" matInput placeholder="Karosserie" >
</mat-form-field>
<mat-form-field>
<input formControlName="childGroup" matInput placeholder="Schrauben" >
</mat-form-field>
</div>
</mat-grid-tile>
<mat-grid-tile>
<button mat-icon-button (click)="addProperty()"><mat-icon>add</mat-icon></button>
<div class="make-scrollable" formArrayName="properties">
<div *ngFor="let property of service.itemForm.controls.properties?.value; let i=index;" class="panel panel-default">
<ng-container [formGroupName]="i">
<mat-form-field>
<input formControlName="key" matInput placeholder="Titel" >
</mat-form-field>
<mat-form-field>
<input formControlName="text" matInput placeholder="Beschreibender Text" >
</mat-form-field>
</ng-container>
</div>
</div>
</mat-grid-tile>
<mat-grid-tile [colspan]="2">
<div class="buttom-row">
<button mat-raised-button color="primary" type="submit" [disabled]="service.itemForm.invalid">Speichern</button>
<button mat-raised-button color="warn" (click)="onClear()">Bereinigen</button>
</div>
</mat-grid-tile>
</mat-grid-list>
</form>
When i click any Button, the console is logging (currently I tried to add a property: (click)="addProperty()")
Console output:
item.component.ts:32 !!! add prop !!!
item.component.ts:26 !!! submit !!!
item.component.ts:44 !!! close !!!
But i expect the following output
Console output:
item.component.ts:32 !!! add prop !!!
Thanks to Julius Dzidzevičius.
He told me to set the button type="button"
Now everything works fine!!!
See below
´´´HTML
<form [formGroup]="service.itemForm" class="normal-form" (ngSubmit)="onSubmit(service.itemForm.value, service.itemForm.valid)">
<mat-grid-list cols="2">
<mat-grid-tile>
<div class="controles-container">
<input type="hidden" formControlName="id" >
<mat-form-field>
<input formControlName="artNr" matInput placeholder="EA0123" >
<mat-error>Artikelnummer zwingend erforderlich</mat-error>
</mat-form-field>
<mat-form-field>
<input formControlName="name" matInput placeholder="Artikelbezeichnung" >
<mat-error>Bezeichnung ist erforderlich</mat-error>
</mat-form-field>
<mat-form-field>
<input formControlName="parentGroup" matInput placeholder="Karosserie" >
</mat-form-field>
<mat-form-field>
<input formControlName="childGroup" matInput placeholder="Schrauben" >
</mat-form-field>
</div>
</mat-grid-tile>
<mat-grid-tile>
<button mat-icon-button type="button" (click)="addProperty()"><mat-icon>add</mat-icon></button>
<div class="make-scrollable" formArrayName="properties">
<div *ngFor="let property of service.itemForm.controls.properties?.value; let i=index;" class="panel panel-default">
<ng-container [formGroupName]="i">
<mat-form-field>
<input formControlName="key" matInput placeholder="Titel" >
</mat-form-field>
<mat-form-field>
<input formControlName="text" matInput placeholder="Beschreibender Text" >
</mat-form-field>
</ng-container>
</div>
</div>
</mat-grid-tile>
<mat-grid-tile [colspan]="2">
<div class="buttom-row">
<button mat-raised-button color="primary" type="submit" [disabled]="service.itemForm.invalid">Speichern</button>
<button mat-raised-button type="button" color="warn" (click)="onClear()">Bereinigen</button>
</div>
</mat-grid-tile>
</mat-grid-list>
</form>
´´´´

Get child form data when called from parent

Hi i have a question about Angular 2 and really don't know how to do that and I need your help :)
I have a child component that have a simple registration form but the submit button on parent template. So when I press the submit button it will get data from child component form.
here is my example.
Parent component ts
import {Component, ViewChild, OnDestroy, Output, EventEmitter} from '#angular/core';
import {GlobalEvent} from 'app/shared/GlobalEvent';
#Component({
selector: 'signup',
templateUrl: 'SignUpModalComponent.html',
styleUrls: ['SignUpModalComponent.scss'],
})
export class SignUpModalComponent implements OnDestroy {
public overlayState: boolean;
public step: number = 1;
public formSubmit: boolean;
#ViewChild('firstModal')
modal: any;
constructor(private modalEventService: GlobalEvent) {
this.modalEventService.modalChangeEvent.subscribe((res: boolean) => {
this.overlayState = res;
if (res) {
this.modal.open();
} else {
this.modal.close();
}
});
}
closeModal(value: boolean): void {
this.modalEventService.close(false);
this.modal.close()
}
ngOnDestroy() {
this.modalEventService.modalChangeEvent.unsubscribe();
}
incrementStep():void {
this.step += 1;
}
decrementStep():void {
this.step -= 1;
}
onFormSubmit(): void {
this.formSubmit = true;
}
}
Parent component html template
<div class="modal-overlay" *ngIf="overlayState"></div>
<modal (onClose)="closeModal(false)" #firstModal >
<modal-header>
<button (click)="firstModal.close()" class="close-btn"><i class="material-icons">close</i></button>
<div class="steps-container">
<span [ngClass]="{'active': step == 1 }">1</span>
<span [ngClass]="{'active': step == 2 }">2</span>
<span [ngClass]="{'active': step == 3 }">3</span>
<span [ngClass]="{'active': step == 4 }">4</span>
</div>
</modal-header>
<modal-content>
<signup-form [hidden]="step != 1" [formSubmit]="formSubmit"></signup-form>
<signup-social ngClass="social-step{{step}}" [step]="step"></signup-social>
</modal-content>
<modal-footer>
<button md-button (click)="decrementStep()" [hidden]="step == 1"><Back</button>
<button md-button (click)="incrementStep(); onFormSubmit()" [hidden]="step != 1">Next></button>
<button md-button (click)="incrementStep()" [hidden]="step == 1 || step == 4">Skip</button>
</modal-footer>
</modal>
Child component ts file
import {Component, OnInit, Input} from '#angular/core';
import {FormBuilder, FormGroup, Validators} from '#angular/forms';
import {CustomValidators} from 'ng2-validation';
import {SignUpFormInterface} from './SignUpFormInterface';
#Component({
selector: 'signup-form',
templateUrl: 'SignUpForm.html',
styleUrls: ['SignUpForm.scss']
})
export class SignUpForm implements OnInit {
signupInfo: FormGroup;
public tmppass: any;
#Input() set formSubmit(sendData: boolean) {
if (sendData) {
}
}
constructor(private formbuilder: FormBuilder) {
}
ngOnInit() {
this.signupInfo = this.formbuilder.group({
email: ['', [CustomValidators.email]],
username: ['', [Validators.required, CustomValidators.min(10)]],
password: ['', [Validators.required, CustomValidators.rangeLength([5, 100]), this.setPass]],
confirmPassword: ['', [Validators.required, CustomValidators.rangeLength([5, 100]), CustomValidators.equal(this.tmppass)]],
fullName: ['', [Validators.required, CustomValidators.min(10)]],
gender: ['', [Validators.required]],
countrys: ['', [Validators.required]],
});
}
setPass(c: any): void {
console.log('sdsd', c.value);
if (c.value) {
this.tmppass = '';
this.tmppass = <string>c.value;
}
}
onSubmit({value, valid}: {value: SignUpFormInterface, valid: boolean}) {
console.log(this.signupInfo);
}
cons() {
console.log(this.signupInfo);
}
}
function validateEmail(c: any) {
let EMAIL_REGEXP = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
return EMAIL_REGEXP.test(c.value) ? c.email = false : c.email = true;
}
Child component html template
<div class="sign-up-form clearfix">
<form novalidate (ngSubmit)="onSubmit(signupInfo)" [formGroup]="signupInfo">
<label>
<input type="file" placeholder="Last Name*" name="lastName"/>
upload an avatar
</label>
<md-input-container>
<input md-input placeholder="Email address*" name="email" formControlName="email"/>
</md-input-container>
<!--<p *ngIf="signupInfo.controls.email.errors?.email">error message</p>-->
<div class="errror-msg" *ngIf="signupInfo.controls.email.errors?.email">
<md-hint>
<span>Name should be minimum 6 characters</span>
</md-hint>
</div>
<p *ngIf="signupInfo.controls.username.errors?.min">error message</p>
<div class="input-wrap" [ngClass]="{'error': signupInfo.controls.username.errors?.min}">
<md-input-container>
<input md-input placeholder="Username*" name="username" formControlName="username"/>
</md-input-container>
<div class="errror-msg" *ngIf="signupInfo.controls.username.errors?.min">
<md-hint>
<span>Name should be minimum 6 characters</span>
</md-hint>
</div>
<div class="errror-msg"
*ngIf="signupInfo.get('username').hasError('minlength') && signupInfo.get('username').touched">
<md-hint>
<span>Name should be minimum 6 characters</span>
</md-hint>
</div>
</div>
<p *ngIf="signupInfo.controls.password.errors?.rangeLength">error xcdfdfd</p>
<md-input-container>
<input md-input placeholder="Password*" formControlName="password"/>
</md-input-container>
<p *ngIf="signupInfo.controls.confirmPassword.errors?.rangeLength">error password</p>
<p *ngIf="signupInfo.controls.confirmPassword.errors?.equal">error equal</p>
<md-input-container>
<input md-input placeholder="Confirm Password*" formControlName="confirmPassword"/>
</md-input-container>
<p *ngIf="signupInfo.controls.fullName.errors?.min">error password</p>
<md-input-container>
<input md-input placeholder="Full Name*" name="fullName" formControlName="fullName"/>
</md-input-container>
<p *ngIf="signupInfo.controls.gender.errors?.required">error password</p>
<md-select placeholder="Gender" formControlName="gender">
<md-option *ngFor="let food of ['react','angular']" [value]="food">
{{ food }}
</md-option>
</md-select>
<p *ngIf="signupInfo.controls.countrys.errors?.required">error password</p>
<md-select placeholder="Country" formControlName="countrys">
<md-option *ngFor="let country of countrys" [value]="country">
{{ country.name }}
</md-option>
</md-select>
<div class="input-wrap">
<md-input-container placeholder="Date of Birth *">
<input md-input placeholder="mm/dd/yyyy" type="text" name="DateofBirth"/>
</md-input-container>
</div>
</form>
</div>
Thanks for help :)

Angular2: issues converting a form's value to a Model with default fields

I am busy with a Stock take form that needs to be posted to a REST API. I have a stockTake model which has three fields that get initialized with default values of 0. the three fields "StockTakeID, IDKey and PackSize" are not part of the angular form where the data needs to be entered. My issue is submitting the model with those three fields with default values to my RestService. When I submit the stockTakeForm.value I get an error as those three fields are not part of the data that's being submitted... Any idea how I can go about getting this to work?
my stock-take.model.ts:
export class StockTakeModel {
constructor(
StockTakeID: number = 0,
IDKey: number = 0,
BarCode: number,
ProductCode: string,
SheetNo: string,
BinNo: string,
Quantity: number,
PackSize: number = 0) { }
}
my stock-take.component.ts:
import { Component, OnInit } from '#angular/core';
import { FormBuilder, FormGroup, Validators } from '#angular/forms';
import { RestService } from '../../services/rest.service';
import { StockTakeModel } from '../../models/stock-take.model';
#Component({
selector: 'stock-take',
templateUrl: './stock-take.component.html',
styleUrls: ['./stock-take.component.css']
})
export class StockTakeComponent implements OnInit {
stockTakeForm: FormGroup;
constructor(private fb: FormBuilder, private restService: RestService) {
this.stockTakeForm = fb.group({
'sheetNo':['', Validators.required],
'binNo':['', Validators.required],
'barcode':['', Validators.required],
'Qty':['', Validators.required]
});
}
submitStockTake(stockTakeModel: StockTakeModel) {
//console.log(stockTakeModel);
this.restService.postStockTake(stockTakeModel)
.subscribe(
(res) => {
console.log(res);
},
(res) => {
console.log("failure: " + res);
}
);
this.stockTakeForm.reset();
}
ngOnInit() {
}
}
my stock-take.component.html:
<div class="row">
<div class="col-md-6 col-md-push-3">
<h1>Stock Take</h1>
<br /><br />
<form [formGroup]="stockTakeForm" role="form" (ngSubmit)="submitStockTake(stockTakeForm.value)">
<input type="text" placeholder="Enter Sheet Number" class="form-control" id="sheetNo" [formControl]="stockTakeForm.controls['sheetNo']" name="sheetNo">
<input type="text" placeholder="Enter Bin Number" class="form-control" id="binNo" [formControl]="stockTakeForm.controls['binNo']" name="binNo">
<input type="number" placeholder="Enter Barcode" class="form-control" id="bCode" [formControl]="stockTakeForm.controls['barcode']" name="barcode">
<input type="number" placeholder="Enter Quantity" clas="form-control" id="Qty" [formControl]="stockTakeForm.controls['Qty']" name="quantity">
<button class="btn btn-block" [disabled]="!stockTakeForm.valid">Submit</button>
</form>
</div>
</div>
updated stock-take.component:
import { Component, OnInit } from '#angular/core';
import { FormBuilder, FormGroup, Validators } from '#angular/forms';
import { RestService } from '../../services/rest.service';
import { StockTakeModel } from '../../models/stock-take.model';
#Component({
selector: 'stock-take',
templateUrl: './stock-take.component.html',
styleUrls: ['./stock-take.component.css']
})
export class StockTakeComponent implements OnInit {
stockTakeForm: FormGroup;
stockTakeModel: StockTakeModel;
constructor(private fb: FormBuilder, private restService: RestService) {
this.stockTakeForm = fb.group({
'sheetNo':['', Validators.required],
'binNo':['', Validators.required],
'barcode':['', Validators.required],
'Qty':['', Validators.required]
});
}
doStockTake(val: any) {
//console.log("val:" + JSON.stringify(val));
this.stockTakeModel = new StockTakeModel(0, 0, val[Object.keys(val)[2]], '', val[Object.keys(val)[0]], val[Object.keys(val)[1]], val[Object.keys(val)[3]], 0);
// console.log(this.stockTakeModel);
console.log(JSON.stringify(this.stockTakeModel));
}
submitStockTake(stockTakeModel: StockTakeModel) {
//console.log(stockTakeModel);
this.restService.postStockTake(stockTakeModel)
.subscribe(
(res) => {
console.log(res);
},
(res) => {
console.log("failure: " + res);
}
);
this.stockTakeForm.reset();
}
ngOnInit() {
}
}
One workaround would to create a new variable, e.g:
stockTakeModel: StockTakeModel;
if that doesn't work (as you said it complained about undefined), you can also instantiate it as an empty Object, like so:
stockTakeModel = {};
EDIT, so you changed your code to something like this: I also added some console.logs to show where it is undefined, as there was a little question about that.
stockTakeModel: StockTakeModel; // undefined at this point (or empty if you have defined it as empty above)!
// use Object keys to access the keys in the val object, a bit messy, but will work!
submitStockTake(val: any) {
this.stockTakeModel =
new StockTakeModel(0, 0, val[Object.keys(val)[2]], '', val[Object.keys(val)[0]],
val[Object.keys(val)[1]], val[Object.keys(val)[3]]);
// console.log(this.StockTakeModel); // now it should have all values!
this.restService.postStockTake(this.stockTakeModel)
.subscribe(d => { console.log(d)} ) // just shortened your code a bit
this.stockTakeForm.reset();
}
EDIT: So finally the last issue is solved, besides the solution above. It's because your StockTakeModel-class wasn't properly declared the value was undefined, or actually empty. So fix your class to:
export class StockTakeModel {
constructor(
public StockTakeID: number = 0, // you were missin 'public' on everyone
public IDKey: number = 0,
public BarCode: number,
public ProductCode: string,
public SheetNo: string,
public BinNo: string,
public Quantity: number,
public PackSize: number = 0) { }
}
Note also that in your 'updated' code you still have (ngSubmit)="submitStockTake(stockTakeForm.value) in your form, so your created doStockTake-method is not called.
I don't understand the construction [formControl] in your template.
There should be at least [ngModel].
Usualy I use, for two-way communication, the [(ngModel)]. Not the [formControl].
So your template code should look like this:
<div class="row">
<div class="col-md-6 col-md-push-3">
<h1>Stock Take</h1>
<br /><br />
<form [formGroup]="stockTakeForm" role="form" (ngSubmit)="submitStockTake(stockTakeForm.value)">
<input type="text" placeholder="Enter Sheet Number" class="form-control" id="sheetNo" [(ngModel)]="stockTakeForm.controls['sheetNo']" name="sheetNo">
<input type="text" placeholder="Enter Bin Number" class="form-control" id="binNo" [(ngModel)]="stockTakeForm.controls['binNo']" name="binNo">
<input type="number" placeholder="Enter Barcode" class="form-control" id="bCode" [(ngModel)]="stockTakeForm.controls['barcode']" name="barcode">
<input type="number" placeholder="Enter Quantity" clas="form-control" id="Qty" [(ngModel)]="stockTakeForm.controls['Qty']" name="quantity">
<button class="btn btn-block" [disabled]="!stockTakeForm.valid">Submit</button>
</form>
</div>
</div>

Can't access the data of the form submitted

I am starting with angular2. I have a simple template driven form and I can access the data in console. But I am having problem with passing the data. Here is my code.
import {Component} from "angular2/core";
#Component({
selector: 'my-template-driven',
template:`
<h2>Sign-up form</h2>
<form (ngSubmit)="onSubmit(f)" #f="ngForm">
<div>
<label for="email">Mail</label>
<input ngControl="email" type="text" id="email" required #email="ngForm">
<span class="validation-error" *ngIf="!email.valid">Not Valid</span>
</div>
<div>
<label for="password">Password</label>
<input ngControl="password" type="text" id="password" required #password="ngForm">
<span class="validation-error" *ngIf="!password.valid">Not Valid</span>
</div>
<div>
<label for="confirm-password">Confirm Password</label>
<input ngControl="confirm-password" type="text" id="confirm-password" required #passwordConfirm="ngForm">
<span class="validation-error" *ngIf="!passwordConfirm.valid">Not Valid</span>
</div>
<button type="submit" [disabled]="!f.valid || password.value !== passwordConfirm.value">Submit</button>
</form>
<h2>You Submitted</h2>
`
})
export class TemplateDrivenFormComponent {
user: {email: '', password: ''};
onSubmit(form){
//console.log(form);
this.user.email = form.value['email'];
//this.user.password = form.controls['password'].value;
}
}
I am getting this angular2.js:23941 ORIGINAL EXCEPTION: TypeError: Cannot set property 'email' of undefined error constantly. How can I access the data of the form submitted.
You don't declare your local correctly, and you must initialize it when you declare it, or in your constructor maybe
user: any;
constructor() {
this.user = {email: "", password: ""} as any;
}
after : you must provide the type.
Html input must have "ngModel" attribute in it.

Form validation not working correctly when user hits login button (Angular 2)

I have a form with username and password, when a user hits the submit button, a error message is displayed stating if one or both fields are blank, I'm trying to add a route to the button so it takes them to the home page, however, when I add a route to the button, it ignores the validation as aspect and will work if fields are blank. I've tried to disable the button so that it's only enabled when the form is valid but I'm getting a bit confused between ngForm and ngFormModel
Thanks
This is my html form
<form [ngFormModel]="loginForm" (ngSubmit)="loginUser(loginForm.value)">
<div class="form-group" [ngClass]="{ 'has-error' : !username.valid && submitAttempt }">
<label class="control-label" for="username">Username</label>
<em *ngIf="!username.valid && submitAttempt">Required</em>
<input id="username" type="text" class="form-control" placeholder="Username" ngControl="username">
</div>
<div class="form-group" [ngClass]="{ 'has-error' : !password.valid && submitAttempt }">
<label class="control-label" for="password">Password</label>
<em *ngIf="password.hasError('required') && submitAttempt">Required</em>
<em *ngIf="password.hasError('minlength') && submitAttempt">Must be at least 8 characters</em>
<input id="password" type="password" class="form-control" placeholder="Password" ngControl="password">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Register</button>
</div>
</form>
And this is my component
import {Component, EventEmitter} from "angular2/core";
import {Router} from "angular2/router";
import {ROUTER_DIRECTIVES} from "angular2/router";
import {Control, ControlGroup, FormBuilder, Validators, FORM_DIRECTIVES} from 'angular2/common';
//import {UsernameValidators} from './usernameValidators';
#Component({
selector: 'LoginHTML',
templateUrl: 'dev/LoginComponents/login-form.component.html',
directives : [FORM_DIRECTIVES]
})
export class LoginHTMLComponent{
loginForm: ControlGroup;
username: Control;
password: Control;
submitAttempt: boolean = false;
form: ControlGroup;
constructor( private builder: FormBuilder, private _router: Router) {
this.username = new Control('', Validators.required)
this.password = new Control('', Validators.compose([Validators.required, Validators.minLength(8)]))
this.loginForm = builder.group({
username: this.username,
password: this.password
});
}
loginUser(user) {
this.submitAttempt = true;
this._router.navigate(['Dashboard']);
}
}
You should be free to do anything with your code, so the form won't try to intervene your loginUser function to navigate to Dashboard. But it does provide you information about form validity that you can make use of:
loginUser(user) {
this.submitAttempt = true;
if (this.loginForm.valid) {
this._router.navigate(['Dashboard']);
}
}