Angular 4 Reset Button Throws Error - html

I have the following form in my HTML element:
<form class="row" name="powerPlantSearchForm" (ngSubmit)="f.valid && searchPowerPlants()" #f="ngForm" novalidate>
<div class="form-group col-xs-3" >
<label for="powerPlantName">PowerPlant Name</label>
<input type="text" class="form-control-small" [ngClass]="{ 'has-error': f.submitted && !powerPlantName.valid }" name="powerPlantName" [(ngModel)]="model.powerPlantName" #powerPlantName="ngModel" />
</div>
<div class="form-group col-xs-3" >
<label for="powerPlantType">PowerPlant Type</label>
<select class="hideLabel form-control" [(ngModel)]="model.powerPlantType" name="powerPlantType" (change)="selectName();">
<option selected="" value="">--Select Type--</option>
<option [ngValue]="powerPlantType" *ngFor="let powerPlantType of powerPlantTypes">
{{ powerPlantType }}
</option>
</select>
</div>
<div class="form-group col-xs-3" [ngClass]="{ 'has-error': f.submitted && !organizationName.valid }">
<label for="organizationName">Organization Name</label>
<input type="text" class="form-control-small" name="powerPlantOrganization" [(ngModel)]="model.powerPlantOrg" #organizationName="ngModel" />
</div>
<div class="form-group col-xs-3" [ngClass]="{ 'has-error': f.submitted && !powerPlantStatus.valid }">
<label for="powerPlantStatus">PowerPlant Active Status</label>
<input type="text" class="form-control-small" name="powerPlantStatus" [(ngModel)]="model.isOnlyActivePowerPlants" #powerPlantStatus="ngModel" />
</div>
<div class="form-group col-md-3 col-xs-4">
<button [disabled]="loading" class="btn btn-primary">Search For PowerPant's...</button>
<img *ngIf="loading" src="data:image/gif;base64,R0lGODlhEAAQAPIAAP///wAAAMLCwkJCQgAAAGJiYoKCgpKSkiH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAADMwi63P4wyklrE2MIOggZnAdOmGYJRbExwroUmcG2LmDEwnHQLVsYOd2mBzkYDAdKa+dIAAAh+QQJCgAAACwAAAAAEAAQAAADNAi63P5OjCEgG4QMu7DmikRxQlFUYDEZIGBMRVsaqHwctXXf7WEYB4Ag1xjihkMZsiUkKhIAIfkECQoAAAAsAAAAABAAEAAAAzYIujIjK8pByJDMlFYvBoVjHA70GU7xSUJhmKtwHPAKzLO9HMaoKwJZ7Rf8AYPDDzKpZBqfvwQAIfkECQoAAAAsAAAAABAAEAAAAzMIumIlK8oyhpHsnFZfhYumCYUhDAQxRIdhHBGqRoKw0R8DYlJd8z0fMDgsGo/IpHI5TAAAIfkECQoAAAAsAAAAABAAEAAAAzIIunInK0rnZBTwGPNMgQwmdsNgXGJUlIWEuR5oWUIpz8pAEAMe6TwfwyYsGo/IpFKSAAAh+QQJCgAAACwAAAAAEAAQAAADMwi6IMKQORfjdOe82p4wGccc4CEuQradylesojEMBgsUc2G7sDX3lQGBMLAJibufbSlKAAAh+QQJCgAAACwAAAAAEAAQAAADMgi63P7wCRHZnFVdmgHu2nFwlWCI3WGc3TSWhUFGxTAUkGCbtgENBMJAEJsxgMLWzpEAACH5BAkKAAAALAAAAAAQABAAAAMyCLrc/jDKSatlQtScKdceCAjDII7HcQ4EMTCpyrCuUBjCYRgHVtqlAiB1YhiCnlsRkAAAOwAAAAAAAAAAAA==" />
</div>
<div class="form-group col-md-3 col-xs-3">
<button class="btn btn-primary" (click)="reset(f)">Reset Search Criteria</button>
</div>
</form>
It renders fine, but when I tried to click the reset button, I get the following error:
ERROR TypeError: _co.reset is not a function
at Object.eval [as handleEvent] (HomeComponent.html:35)
at handleEvent (core.es5.js:12004)
at callWithDebugContext (core.es5.js:13465)
at Object.debugHandleEvent [as handleEvent] (core.es5.js:13053)
at dispatchEvent (core.es5.js:8602)
at core.es5.js:9213
at HTMLButtonElement.<anonymous> (platform-browser.es5.js:2651)
at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:424)
at Object.onInvokeTask (core.es5.js:3881)
at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
Here is my component class:
export class HomeComponent implements OnInit {
// Represents the PowerPlantTypes
powerPlantTypes = ['RampUpType', 'OnOffType'];
// Represents the search form
model: any = {};
// currentUser: User;
// represents the list of PowerPlant data
powerPlants: PowerPlant[];
users: User[] = [];
constructor(private userService: UserService, private powerPlantService: PowerPlantService) {
// this.currentUser = JSON.parse(localStorage.getItem('currentUser'));
}
ngOnInit() {
this.allPowerPlants();
}
selectName() {
alert(this.model.powerPlantType);
}
searchPowerPlants(): void {
const powerPlantSearchParams = new PowerPlantSearchParams(
this.model.powerPlantType,
this.model.powerPlantOrganization,
this.model.powerPlantName,
this.model.page,
this.model.powerPlantStatus);
this.powerPlantService.searchPowerPlants(powerPlantSearchParams).subscribe(result => {
this.powerPlants = <PowerPlant[]> result;
});
}
allPowerPlants(onlyActive: boolean = false, page: number = 1): void {
this.powerPlantService.allPowerPlants(onlyActive, page).subscribe(result => {
this.powerPlants = <PowerPlant[]> result;
});
}
}
What is this error conveying?

According to the Angular docs it seems you should call f.reset() not reset(f)

Check your component class if the function named reset actually exists.

use following code with Reset Search Criteria button
(click)='form.reset()'
no parameter is required
(click)="reset(form)" // wrong

Related

Angular validations showing during the page load

We are working on the Angular 4 form and set some validations on the input field but the validation is showing when the page load's but we want the validation when the form is submitted or the field is not valid or filled.
Component.html
<div class="headerbutton-group row">
<i class="fa fa-save header-buttons" tooltip ="Save" tabindex="1" (click)="onSave($event)"></i>
<i class="fa fa-close header-buttons" tooltip ="Close" (click)="onCancel($event)"></i>
</div>
<form [formGroup]="editForm" class="col-md-12 ">
<div class="form-group row">
<div class="col-md-6 padding-Mini">
<label class="col-md-12 col-form-label padding-bottom-Mini" for="txtName">Name</label>
<div class="col-md-12">
<input type="text" id="txtName" name="txtName" class="form-control" placeholder="Name" formControlName="name" [class.is-invalid]="!editForm.controls.name.valid" [class.is-valid]="editForm.controls.name.valid" required>
<div class="invalid-feedback" [style.visibility]=
"editForm.controls.name.valid ? 'hidden':'visible'"> Name is required</div>
</div>
</div>
<div class="col-md-6 padding-Mini">
<label class="col-md-12 col-form-label padding-bottom-Mini" for="txtName">Description</label>
<div class="col-md-12">
<input type="text" id="txtDescription" name="txtDescription" class="form-control"
placeholder="Description" formControlName="description">
</div>
</div>
</div>
</form>
Component.ts
#Component({
selector: 'app-edit-form',
templateUrl: './component.html'
})
export class LoginFormComponent implements OnInit {
constructor(fb:FormBuilder) {
public editForm: FormGroup = new FormGroup({
name : new FormControl('', Validators.required),
description : new FormControl(''),
});
}
public onSave(e): void {
if (this.editForm.valid) {
e.preventDefault();
this.save.emit(this.editForm.value);
} else {
this.validateAllFormFields(this.editForm);
}
}
public onCancel(e): void {
e.preventDefault();
this.closeForm();
}
private validateAllFormFields(formGroup: FormGroup) {
Object.keys(formGroup.controls).forEach(field => {
const control = formGroup.get(field);
if (control instanceof FormControl) {
control.markAsTouched({ onlySelf: true });
} else if (control instanceof FormGroup) {
this.validateAllFormFields(control);
}
});
}
}
// Tried this too editForm.controls.name.pristine
We don't know what we are missing. Kindly help us, with useful documents/ Demo's.
try changing this
<div class="invalid-feedback" [style.visibility]="editForm.controls.name.valid ? 'hidden':'visible'">
Name is required
</div>
to this
<div class="invalid-feedback" *ngIf="!editForm.controls.name.valid && editForm.controls.name.touched">
Name is required
</div>
adding a test on "touched" will fix your problem !

Angular form error-TypeError: Class constructor Validators cannot be invoked without 'new'

I'm getting the following angular form error -
ERROR TypeError: Class constructor Validators cannot be invoked without 'new'
at forms.js:1480
at Array.map (<anonymous>)
at _executeValidators (forms.js:1476)
at FormControl.validator (forms.js:1418)
at FormControl._runValidator (forms.js:4089)
at FormControl.updateValueAndValidity (forms.js:4050)
at new FormControl (forms.js:4656)
at FormBuilder.control (forms.js:8951)
at FormBuilder._createControl (forms.js:9011)
at forms.js:8990
Can someone please tell me what I am missing?
My HTML:
<form class="formLogin" [formGroup]="personalForm" (ngSubmit)="onSubmit()">
<div class="form-group rtl">
<label class="col-sm-3 control-label pull-right" for="mail"> your email</label>
<div class="col-sm-9">
<input type="text" formControlName="mail" [value]="person.Email" placeholder="myAddress#gmail.com" class="form-control ltr textBox" email [ngClass]="{ 'is-invalid': submitted && f.mail.errors }" />
<div *ngIf="submitted && f.mail.errors" class="invalid-feedback">
<div *ngIf="f.mail.errors.required">requird</div>
<div *ngIf="f.mail.errors.email">invalid address!</div>
</div></div>
</div>
<br><br>
<div class="form-group rtl">
<label class="col-sm-3 control-label pull-right" for="phone">your phone</label>
<div class="col-sm-9">
<input type="text" formControlName="phone" [value]="person.Phone" class="form-control ltr textBox" placeholder="000-0000000" [ngClass]="{ 'is-invalid': submitted && f.phone.errors }" />
<div *ngIf="submitted && f.phone.errors" class="invalid-feedback">
<div *ngIf="f.phone.errors.required">requird!</div>
<div *ngIf="f.phone.errors.pattern">digits only!</div>
</div></div>
</div>
<br><br>
<div class="form-group rtl">
<label class="col-sm-3 control-label pull-right" for="username">your username</label>
<div class="col-sm-9">
<input type="text" (focus)="incorrectData=false" [value]="person.UserName" formControlName="username" class="form-control textBox " [ngClass]="{ 'is-invalid': submitted && f.username.errors }" />
<div *ngIf="submitted && f.username.errors" class="invalid-feedback">
<div *ngIf="f.username.errors.required">required!</div>
</div></div>
</div>
<br><br>
<div class="form-group rtl">
<label class="col-sm-3 control-label pull-right" for="password">your password</label>
<div class="col-sm-9">
<input type="password" (focus)="incorrectData=false" [value]="person.Password" minlength="6" formControlName="password" class="form-control textBox" [ngClass]="{ 'is-invalid': submitted && f.password.errors }" />
<div *ngIf="submitted && f.password.errors" class="invalid-feedback">
<div *ngIf="f.password.errors.required">requird!</div>
<div *ngIf="f.password.errors.minlength">password length minimum 6 letters!</div>
</div></div>
</div>
<br>
</form>
My ts:
import { Component, OnInit } from '#angular/core';
import { UserService } from '../../../services/user.service';
import { User,UserEnum } from 'src/app/classes/User';
import { FormBuilder, FormGroup,Validators} from '#angular/forms';
#Component({
selector: 'app-personal-details',
templateUrl: './personal-details.component.html',
styleUrls: ['./personal-details.component.css']
})
export class PersonalDetailsComponent implements OnInit {
person:User;
personalForm:FormGroup;
submitted :boolean;
constructor(private userSer:UserService,
private formBuilder: FormBuilder){ }
ngOnInit() {
this.person=this.userSer.userDetailes;
this.personalForm = this.formBuilder.group({
email:['',[Validators.required,Validators.email]],
password: ['', [Validators.required,Validators.minLength(6),Validators]],
username: ['', Validators.required],
phone:['',[Validators.required,Validators.maxLength(10),Validators.minLength(9),Validators.pattern('[0-9]*')]]});}
get f()
{ return this.personalForm.controls; }
saveUser() {}
onSubmit()
{
this.submitted = true;
// stop here if form is invalid
if (this.personalForm.invalid)
{return;}
this.saveUser();}
}
userService:
#Injectable({
providedIn: 'root'
})
export class UserService {
userDetailes:User=null;
}
I have good form imports for my app.module and other forms in my project work well. I think the problem is in this component.
instead of:
password: ['',
[Validators.required,Validators.minLength(6),Validators]],
i had to write:
password: ['',
[Validators.required,Validators.minLength(6),Validators.maxLength(10)]],
just as written above, your problem is because you are referencing the validators in a wrong manner. You need to include the method you are trying to call or invoke. In this case, your line
password: ['', [Validators.required,Validators.minLength(6),Validators]],
Should be
password: ['', [Validators.required,Validators.minLength(6),Validators.maxLength(20)]],// or any other measure you wish to put in place. Validators is the problem here

Form group dropdown menu content not present in json, Angular 6

I have made a form group where the purpose is to register cars.
On submit it is generating a JSON from the values inserted.
The issue is that the value from the dropdown menu is not present in the JSON.
The dropdown menu is populated with the choices shown below and is the first entry in the form group.
The label names and error messages are in Norwegian but the essence should be there.
<div class="jumbotron">
<div class="container">
<div class="row">
<div class="col-md-3 col-sm-12 offset-md-4">
<h3>Fyll inn</h3>
<form name="form" (ngSubmit)="f.form.valid && onSubmit()" #f="ngForm" novalidate>
<div class="form-group">
<label for="CarType">Bil type</label>
<select id="CarType" name="CarType" [(ngModel)]="CarType" class="form-control">
<option [ngValue]="CarType" *ngFor="let CarType of CarTypes" [value]="CarType.Id">{{CarType.Name}}</option>
</select>
</div>
<div class="form-group">
<label for="LicensePlate">Skiltnummer</label>
<input type="text" class="form-control" name="LicensePlate" [(ngModel)]="model.LicensePlate" #LicensePlate="ngModel" [ngClass]="{ 'is-invalid': f.submitted && LicensePlate.invalid }" required />
<div *ngIf="f.submitted && LicensePlate.invalid" class="invalid-feedback">
<div *ngIf="LicensePlate.errors.required">Skiltnummer er påkrevd</div>
</div>
</div>
<div class="form-group">
<label for="KilometersDriven">Kilometerstand</label>
<input type="number" class="form-control" name="KilometersDriven" [(ngModel)]="model.KilometersDriven" #KilometersDriven="ngModel" [ngClass]="{ 'is-invalid': f.submitted && KilometersDriven.invalid }" required />
<div *ngIf="f.submitted && KilometersDriven.invalid" class="invalid-feedback">
<div *ngIf="KilometersDriven.errors.required">Kilometerstand er påkrevd</div>
</div>
</div>
<div class="form-group">
<label for="Seats">Antall seter</label>
<input type="number" class="form-control" name="Seats" [(ngModel)]="model.Seats" #Seats="ngModel" [ngClass]="{ 'is-invalid': f.submitted && Seats.invalid }" required />
<div *ngIf="f.submitted && Seats.invalid" class="invalid-feedback">
<div *ngIf="Seats.errors.required">Antall seter er påkrevd</div>
</div>
</div>
<div class="form-group">
<label for="Gears">Antall gir</label>
<input type="number" class="form-control" name="Gears" [(ngModel)]="model.Gears" #Gears="ngModel" [ngClass]="{ 'is-invalid': f.submitted && Gears.invalid }" required />
<div *ngIf="f.submitted && Gears.invalid" class="invalid-feedback">
<div *ngIf="Gears.errors.required">Antall gir er påkrevd</div>
</div>
</div>
<div class="form-group">
<button class="btn btn-primary">Registrer</button>
</div>
</form>
</div>
</div>
</div>
</div>
import { Component, OnInit } from '#angular/core';
import { CarType } from 'src/shared/models/cartype.model';
#Component({
selector: 'app-add-car',
templateUrl: './add-car.component.html',
styleUrls: ['./add-car.component.css']
})
export class AddCarComponent implements OnInit {
CarTypes: CarType[] = [
{ Id: 1, Name: 'SUV' },
{ Id: 2, Name: 'Coupe' },
{ Id: 3, Name: 'Sedan' }
]
model: any = {};
onSubmit() {
console.log(this.model)
alert('SUCCESS \n\n' + JSON.stringify(this.model))
}
constructor() { }
ngOnInit() {
}
}
export class CarType {
Id: number;
Name: String;
}
To the right is a link to the fill in form on the website.
To the right is a image of the JSON reply created from the previous picture
{LicensePlate: "RH123123", KilometersDriven: 120000, Seats: 5, Gears: 6}
You didn't bind it with the model object [(ngModel)]="CarType"
<select id="CarType" name="CarType" [(ngModel)]="model.carType" class="form-control">
<option [ngValue]="CarType" *ngFor="let CarType of CarTypes" [value]="CarType.Id">{{CarType.Name}}</option>
</select>

Error + JSON + <select> + <option>

I'm getting a very strange error after I upgraded to Angular 6.0.9. My template has a select, where there is an opnion with a value of "" and an "Select an Option" label, and the other options are generated by a list that comes from the bank.
So when I need to clear the form I call the formBuilder again. However, when I clean the form, a request occurs to api and consequently a json error, warning that it can not serialize a null value.
During the reset of the form I do not call any method that triggers the API, so I'm not sure what to do.
It is worth mentioning that the application still works, but it presents the user with an error message, since I have an interceptor that receives all errors and prints in a snack bar...
Template:
<select class="form-control" id="selectTipoDocumento" formControlName="tipoDocumento" [compareWith]="equals"
[class.is-valid]="this.docForm.controls['tipoDocumento'].valid &&
(this.docForm.controls['tipoDocumento'].touched || this.docForm.controls['tipoDocumento'].dirty)"
[class.is-invalid]="!this.docForm.controls['tipoDocumento'].valid &&
(this.docForm.controls['tipoDocumento'].touched || this.docForm.controls['tipoDocumento'].dirty)">
<option value="">Selecione um tipo</option>
<option *ngFor="let tipo of tiposDocumento" [ngValue]="tipo">{{tipo?.nome}}</option>
</select>
Component:
export class DocumentoDetalheComponent implements OnInit {
docForm: FormGroup;
tiposDocumento: TipoDocumento[];
documento: Documento = new Documento();
constructor(
private fb: FormBuilder,
private tipoDocumentoService: TipoDocumentoService,
private documentoService: DocumentoService,
private route: ActivatedRoute
) {}
ngOnInit() {
const idRota: string = this.route.snapshot.params["id"];
this.createFormGroup();
this.tipoDocumentoService.findAll().subscribe(
obj => {
this.tiposDocumento = obj;
},
error => { }
).unsubscribe;
if (idRota != null){
this.documentoService.findById(idRota).subscribe(
obj => {
this.documento = obj;
this.docForm.setValue({
tipoDocumento: this.documento.tipoDocumento,
resumo: this.documento.resumo,
observacao: this.documento.observacao
});
},
error => { }
);}
}
onSubmit() {
let docTemp: Documento = this.docForm.value;
this.documento.tipoDocumento = docTemp.tipoDocumento;
this.documento.resumo = docTemp.resumo;
this.documento.observacao = docTemp.observacao;
if (this.documento.id == null) {
this.save(this.documento);
} else {
this.update(this.documento);
}
}
save(documento: Documento) {
this.documentoService
.insert(documento)
.subscribe(response => console.log(response));
}
update(documento: Documento) {
this.documentoService.update(documento).subscribe(response => console.log(response));
}
createFormGroup() {
this.docForm = this.fb.group({
tipoDocumento: ["", [Validators.required]],
resumo: ["",[Validators.required, Validators.minLength(5), Validators.maxLength(60)]],
observacao: ["", [Validators.maxLength(500)]]
});
}
limparForm() {
this.createFormGroup();
}
equals(tp1: TipoDocumento, tp2: TipoDocumento) {
return tp1.id === tp2.id
}
voltar() {}
}
API error:
2018-07-16 10:05:43.186 WARN 4996 --- [ tomcat-http--5] .w.s.m.s.DefaultHandlerExceptionResolver : Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of `br.mp.mpce.sge.domain.TipoDocumento` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value (''); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `br.mp.mpce.sge.domain.TipoDocumento` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('')
at [Source: (PushbackInputStream); line: 1, column: 579] (through reference chain: br.mp.mpce.sge.domain.Documento["tipoDocumento"])
I found the solution. The problem was in my formGroup, where I was using ngSubmit, so all buttons in my form were submitting API requests. So, the solution was to remove ngSubmir from the form, as well as manually set, in the event (click), the necessary methods.
<form [formGroup]="docForm" novalidate>
<div class="card">
<div class="card-body">
<div class="form-group row" *ngIf="documento?.id != null">
<div class="form-group col-md-3">
<label for="setor">Nº Protocolo: </label>
</div>
<div class="form-group col-md-6">
{{documento?.codigo}}/{{documento?.ano}}
</div>
</div>
<div class="form-group row" *ngIf="documento?.id != null">
<div class="form-group col-md-3">
<label for="setor">Setor cadastro: </label>
</div>
<div class="form-group col-md-6">
{{documento?.setorCadastro?.nome}}
</div>
</div>
<div class="form-group row">
<div class="form-group col-md-3">
<label for="selectTipoDocumento">Tipo de Documento: </label>
</div>
<div class="form-group col-md-6">
<select class="form-control" id="selectTipoDocumento" formControlName="tipoDocumento" [compareWith]="equals"
[class.is-valid]="this.docForm.controls['tipoDocumento'].valid &&
(this.docForm.controls['tipoDocumento'].touched || this.docForm.controls['tipoDocumento'].dirty)"
[class.is-invalid]="!this.docForm.controls['tipoDocumento'].valid &&
(this.docForm.controls['tipoDocumento'].touched || this.docForm.controls['tipoDocumento'].dirty)">
<option value="">Selecione um tipo</option>
<option *ngFor="let tipo of tiposDocumento" [ngValue]="tipo">{{tipo?.nome}}</option>
</select>
</div>
<div class="form-group col-md-3 invalid-feedback d-block"
*ngIf="!this.docForm.controls['tipoDocumento'].valid && (this.docForm.controls['tipoDocumento'].touched || this.docForm.controls['tipoDocumento'].dirty)">
Tipo dodocumento é obrigatório
</div>
</div>
<div class="form-group row">
<div class="form-group col-md-3">
<label for="inputResumo">Resumo: </label>
</div>
<div class="form-group col-md-6">
<input type="text" class="form-control" id="inputResumo" formControlName="resumo" placeholder="Resumo do documento" maxlength="60"
autocomplete="off"
[class.is-valid]="this.docForm.controls['resumo'].valid && (this.docForm.controls['resumo'].touched || this.docForm.controls['resumo'].dirty)"
[class.is-invalid]="!this.docForm.controls['resumo'].valid && (this.docForm.controls['resumo'].touched || this.docForm.controls['resumo'].dirty)">
</div>
<div class="form-group col-md-3 invalid-feedback d-block"
*ngIf="!this.docForm.controls['resumo'].valid && (this.docForm.controls['resumo'].touched || this.docForm.controls['resumo'].dirty)">
Resumo é obrigatório (5 a 60 caracteres)
</div>
</div>
<div class="form-group row">
<div class="form-group col-md-3">
<label for="inputObservacao">Observação: </label>
</div>
<div class="form-group col-md-6">
<textarea type="text" class="form-control" id="inputObservacao" formControlName="observacao" rows="5">
</textarea>
</div>
</div>
<div class="form-group row">
<div class="form-group col-md-3">
</div>
<div class="form-group col-md-2">
<button class="btn btn-primary btn-block" (click)="limparForm()">Limpar</button>
</div>
<div class="form-group col-md-2">
<button class="btn btn-success btn-block"[disabled]="!docForm.valid" (click)="onSubmit()">Salvar</button>
</div>
<div class="form-group col-md-2">
<a class="btn btn-primary btn-block" [routerLink]="['/']">Voltar</a>
</div>
</div>
</div>
</div>
</form>

Refresing the page on (submit) process Angular2 & Firebase

I´m trying to apply Firebase to the Admin HTML template that I found yesterday.
In the register page when I click on Sign in it reload the page instead of do the Firebase createUserWithEmailAndPass process.
This is my HTML code:
<form [formGroup]="form" (submit)="registrar(form.value)" class="form-horizontal">
<div class="form-group row" [ngClass]="{'has-error': (!name.valid && name.touched), 'has-success': (name.valid && name.touched)}">
<label for="inputName3" class="col-sm-2 control-label">Nombre</label>
<div class="col-sm-10">
<input [formControl]="name" type="text" class="form-control" id="inputName3" placeholder="Nombre completo">
</div>
</div>
<div class="form-group row" [ngClass]="{'has-error': (!email.valid && email.touched), 'has-success': (email.valid && email.touched)}">
<label for="inputEmail3" class="col-sm-2 control-label">NIF</label>
<div class="col-sm-10">
<input [formControl]="email" type="text" class="form-control" id="inputEmail3" placeholder="NIF/DNI">
</div>
</div>
<div class="form-group row" [ngClass]="{'has-error': (!password.valid && password.touched), 'has-success': (password.valid && password.touched)}">
<label for="inputPassword3" class="col-sm-2 control-label">Contraseña</label>
<div class="col-sm-10">
<input [formControl]="password" type="password" class="form-control" id="inputPassword3" placeholder="Introduce una contraseña">
</div>
</div>
<div class="form-group row" [ngClass]="{'has-error': (!repeatPassword.valid && repeatPassword.touched), 'has-success': (repeatPassword.valid && repeatPassword.touched)}">
<label for="inputPassword4" class="col-sm-2 control-label"></label>
<div class="col-sm-10">
<input [formControl]="repeatPassword" type="password" class="form-control" id="inputPassword4" placeholder="Repite la contraseña">
<span *ngIf="!passwords.valid && (password.touched || repeatPassword.touched)" class="help-block sub-little-text">Las contraseñas no coinciden.</span>
</div>
</div>
<div class="form-group row">
<div class="offset-sm-2 col-sm-10">
<button [disabled]="!form.valid" type="submit" class="btn btn-default btn-auth">Confirmar registro</button>
</div>
</div>
</form>
And this my functions:
nuevoUsuario(email, password) {
console.log(email);
return this.af.auth.createUser({
email: email,
password: password
});
}
public registrar(datos: Object): void {
this.submitted = true;
if (this.form.valid) {
// your code goes here
const formarCorreo = this.email.value +' #maimona.com';
console.log(formarCorreo);
this.afService.nuevoUsuario(formarCorreo.toLowerCase,
this.password).then((user) => {
this.afService.saveUserInfoFromForm(formarCorreo.toLowerCase,
this.name, this.email).then(() => {
// this.router.navigate(['login']);
})
.catch((error) => {
this.error = error;
console.log(error);
});
})
.catch((error) => {
this.error = error;
console.log(error);
});
}
}
I don´t know why when I press "Confirmar registro" it reload the page instead of do the function. Well it enter the function until
console.log(formarCorreo);
You can change the type of the button to button from submit and add the function to the buttons click
<button [disabled]="!form.valid" class="btn btn-default btn-auth"
type="button" <-- type
(click)="registrar(form.value)" <--click
>Confirmar registro</button>
type="submit will make elements to reload the form
By default, html <form> elements navigate to their target attribute.
To override this (since this is what you'll want most of the time in a single-page app), angular provides the (ngSubmit) convenience event (which uses event.preventDefault(), which would solve your case anyway, but is cleanear)
<button type="submit"> is doing HTTP request to the server. It's the same like <input type="submit">.
You can change it to ordinary <button> or prevent the submitting a form using events.