Ionic2 serve shows blank screen after using formbuilder - ionic-framework

I have a Login page. It was working fine. I changed the login form to use FormBuilder.
There is no error during build process or any reported in the developer tool. But the application shows blank screen when running with ionic serve.
Below is the code changed in login.html.
<form [formGroup]="loginForm" (ngSubmit)="login(loginForm.value)" >
<ion-row>
<ion-col>
<ion-list inset>
<ion-item>
<ion-input type="text" placeholder="Username" formControlName="username" ></ion-input>
</ion-item>
<p *ngIf="username.hasError('required') && username.touched" danger>Username is required</p>
<ion-item>
<ion-input type="password" placeholder="Password" formControlName="password"></ion-input>
</ion-item>
<p *ngIf="password.hasError('required') && password.touched" danger>Password is required</p>
</ion-list>
</ion-col>
</ion-row>
<ion-row>
<ion-col class="signup-col">
<button ion-button class="submit-btn" full type="submit" [disabled]="!loginForm.valid">Login</button>
<button ion-button class="register-btn" block clear (click)="createAccount()">Create New Account</button>
</ion-col>
</ion-row>
</form>
Below is the code changed in login.ts.
import { Component } from '#angular/core';
import { NavController, AlertController, LoadingController, Loading } from 'ionic-angular';
import { FormBuilder, FormGroup, FormControl, Validators } from '#angular/forms';
import { AuthService } from '../../providers/auth-service';
import { RegisterPage } from '../register/register';
import { HomePage } from '../home/home';
#Component({
selector: 'page-login',
templateUrl: 'login.html'
})
export class LoginPage {
loading: Loading;
registerCredentials = {username: '', password: ''};
loginForm: FormGroup;
username: FormControl;
password: FormControl;
constructor(private nav: NavController, private auth: AuthService,
private alertCtrl: AlertController, private loadingCtrl: LoadingController,
public formBuilder: FormBuilder) {
this.loginForm = formBuilder.group({
username: ['', Validators.required],
password: ['', Validators.required],
});
this.username = this.loginForm['username'];
this.password = this.loginForm['password'];
}

Related

How to pass data to another page from Input Form in IONIC 5

I have an input form with 3 text input. The only thing i want it is to send this 3 datas to another page that i called "Identity". I'd like to know how can do to send this 3 datas to another page using ionic 5. I want to create a signing step by step style. someone can help please?
REGISTER.PAGE.HTML
<ion-content fullscreen="true" class="background-contact">
<div class="fixed">
<div class="div-3">
<div align="center">
<b>IDENTIFICATION</b>
</div>
<ion-label position="stacked" class="title">E-mail</ion-label>
<div align="center" class="input-class">
<ion-input autofocus="true" ngModel name="email" type="email" placeholder="informez votre email"></ion-input>
</div>
<div class="line">
<ion-label position="stacked" class="title">Mot de passe</ion-label>
<div align="center" class="input-class">
<ion-input ngModel name="password" type="password" placeholder="informez votre mot de passe"></ion-input>
</div>
</div>
<!-- <div class="line">
<ion-label position="stacked" class="title">Téléphone</ion-label>
<div align="center" class="input-class">
<ion-input autofocus="true" ngModel name="phone" type="text" placeholder="Tapez votre numéro de tel" (keypress)="numberOnlyValidation($event)"></ion-input>
</div>
</div> -->
<div class="line">
<ion-label position="stacked" class="title">Pays</ion-label>
<div align="center" >
<ion-select cancelText="Fermer" okText="Confirmer" ngModel name="cod_country">
<ion-select-option value="">Dans quel pays êtes-vous?</ion-select-option>
<ion-select-option value="{{item?.id}}" *ngFor="let item of country">{{item?.name}}</ion-select-option>
</ion-select>
</div>
</div>
<div class="line">
<div align="center" class="input-class">
<ion-button (click)="goToAboutPage()" expand="block" color="primary"><ion-spinner *ngIf="loading"></ion-spinner> CONFIRMER <ion-icon name="checkmark-done"></ion-icon></ion-button>
</div>
</div>
</div>
</div>
</ion-content>
RESGISTER.PAGE.TS
import { Component, OnInit } from '#angular/core';
import { AlertController, NavController, ToastController } from '#ionic/angular';
import { AuthService } from 'src/app/services/auth.service';
import { NgForm } from '#angular/forms';
import { AlertService } from 'src/app/services/alert.service';
import {IdentityPage} from 'src/app/identity/identity.page';
import { Router } from '#angular/router';
#Component({
selector: 'app-register',
templateUrl: './register.page.html',
styleUrls: ['./register.page.scss'],
})
export class RegisterPage implements OnInit {
loading: boolean;// loading chamando
country: any;
password:any;
private cod_country;
constructor(
private authService: AuthService,
private navCtrl: NavController,
private alertService: AlertService,
public alertController: AlertController,
private toast: ToastController,
private router: Router,
) {
this.getCountry();
}
ngOnInit() {
}
//Get all country list
getCountry(){
this.authService.getCountry().subscribe(country=>{
this.country = country;
})
}
// navigate to about page
goToAboutPage(data) {
this.router.navigate(['/identity'],{
queryParams:data
})
}
}
There are Multiple Ways to pass data from 1 page to other page.
Method 1:
Use Angular Router with params
Page 1:
goToNewPage(){
this.router.navigate(['/identity'],{
queryParams: JSON.Stringify(data)
})
}
Page 2:
import {ActivatedRoute} from '#angular/router';
constructor(private activatedRoute: ActivatedRoute){
this.activatedRoute.queryParams.subscribe(params => {
console.log(params)
});
}
Method 2:
Create a GlobalDataProviderService.
Run Command:
ionic generate service globaldata
inside Globaldata class:
public static userObject:any;
Import this class on your both pages and initialize your variable.
Page 1:
goToNewPage(){
GlobaldataService.userObject = YourData;
this.router.navigate(['/identity'])
}
Page 2:
import this class:
inside Constructor or lifeCycle Hook.
yourVaribale = GlobaldataService.usrObject;
Method 3 for Real time Update:
Check my Other Answer: Real Time Data Update
Page 1 html code
<ion-row>
<ion-col size="12">
<ion-item>
<ion-label position="stacked">E-Mail</ion-label>
<ion-input type="email" [(ngModel)]="email"></ion-input>
</ion-item>
<ion-item>
<ion-label position="stacked">Password</ion-label>
<ion-input type="password" [(ngModel)]="password"></ion-input>
</ion-item>
<ion-item>
<ion-label>Country</ion-label>
<ion-select placeholder="Select Country" [(ngModel)]="country">
<ion-select-option value="India">India</ion-select-option>
<ion-select-option value="Usa">Usa</ion-select-option>
</ion-select>
</ion-item>
</ion-col>
<ion-col size="12" class="ion-text-center">
<ion-button (click)="goToAboutPage()" expand="block" shape="round">
Click me
</ion-button>
</ion-col>
</ion-row>
Page 1 ts code
public country: string;
public email: string;
public password: string;
constructor(public nav: NavController) {}
goToAboutPage() {
let params: any = {
country: this.country,
email: this.email,
password: this.password
}
this.nav.navigateForward('/identity', { state: params }); // params to pass object/array
}
Page 2
constructor(public router: Router){
if (router.getCurrentNavigation().extras.state) {
const params = this.router.getCurrentNavigation().extras.state;
console.log(params.email)
console.log(params.password)
console.log(params.country)
}
}

Login using API in Ionic 6

## login.page.ts ##
import { Component, OnInit } from '#angular/core';
import { AuthService } from 'src/services/auth/auth.service';
import { NavController } from '#ionic/angular';
import { AlertService } from 'src/services/alert/alert.service';
import { NgForm } from '#angular/forms';
#Component({
selector: 'app-login',
templateUrl: './login.page.html',
styleUrls: ['./login.page.scss']
})
export class LoginPage implements OnInit {
constructor(
private authService: AuthService,
private navCtrl: NavController,
private alertService: AlertService
) { }
ngOnInit() {
}
onLogin(form: NgForm) {
this.authService.login(form.value.username, form.value.password).subscribe(
() => {
this.alertService.presentToast("Logged In");
this.navCtrl.navigateRoot('/welcome');
},
error => {
console.log(error);
},
() => {
this.alertService.presentToast("Failed");
this.navCtrl.navigateRoot('/login');
}
);
}
}
## login.page.scss ##
ion-content.background{
--background: url(../../assets/img/staffandtruck.jpg) 0 0/100% 100% no-repeat;
}
## login.page.html ##
<ion-content padding class="background">
<ion-card>
<img src="assets/img/logo2.png"/>
</ion-card>
<ion-card>
<ion-card-content>
<form #form="ngForm" (ngSubmit)="onLogin(form)">
<ion-item>
<ion-icon slot="start" name="person-circle"></ion-icon>
<ion-label position="floating">Staff ID</ion-label>
<ion-input type="email" name="username" ngModel required></ion-input>
</ion-item>
<ion-item>
<ion-icon slot="start" name="key"></ion-icon>
<ion-label position="floating">Password</ion-label>
<ion-input type="password" name="password" ngModel required></ion-input>
</ion-item>
<ion-card-content>
<ion-button expand="block" color="primary" type="submit">Log in</ion-button>
</ion-card-content>
</form>
</ion-card-content>
</ion-card>
</ion-content>
i am new here and beginner in Ionic Framework. Is there anyone can help me and teach me on how to create a login using API that call username and password without create a Model for User? I don't know how to startup and implement this API. This is my environment setup for Ionic.
My environment setup for Ionic. This is for environment service that calling API for login EnvService.ts. This is for auth service AuthService.ts. But, that all not functioning as I wish.

Not able to show the errors after user type some value in Ionic

I am working in Ionic Project and I have used form but when I am showing the errors so my errors are not coming.
This is my orderform.html:
<ion-content padding>
<p class="newp11">Order Number: {{orderpa}}</p>
<h2 class="myformh2">Fill Your Account Detail's</h2>
<form [formGroup]="cancelorderde" (ngSubmit)="cancelorderDetails()">
<ion-list>
<ion-item class="newitem2">
<ion-input placeholder="IFSC Code*" type="text" formControlName="ifsc_code" required></ion-input>
<p *ngIf="cancelorderde.controls['ifsc_code'].errors" class="danger" padding>IFSC Code Is Not Valid</p>
</ion-item>
<div>
<button [disabled]="!cancelorderde.valid" ion-button type="submit" class="newbtn11" color="primary" block>Cancel Order</button>
</div>
</ion-list>
</form>
</ion-content>
In this html, I have shown one error but it is not coming as the user type some wrong input.
This is my orderform.ts:
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import {Validators, FormBuilder, FormGroup } from '#angular/forms';
#IonicPage()
#Component({
selector: 'page-cancelorder',
templateUrl: 'cancelorder.html',
})
export class CancelorderPage {
cancelorderde : FormGroup;
orderpa: any;
constructor(public navCtrl: NavController, public navParams: NavParams,
private formBuilder: FormBuilder) {
this.cancelorderde = this.formBuilder.group({
holder_name: ['', Validators.required],
bank_name: ['', Validators.required],
branch_name: ['', Validators.required],
account_number: ['', Validators.required],
ifsc_code: ['', Validators.compose([
Validators.required,
Validators.pattern('^[A-Za-z]{4}[a-zA-Z0-9]{7}$')
])],
mobile_number: ['', Validators.compose([
Validators.maxLength(10),
Validators.minLength(10),
Validators.required
])],
reason: ['', Validators.required],
remark: ['', Validators.required],
});
this.orderpa = navParams.get('orderno');
}
ionViewDidLoad() {
console.log('ionViewDidLoad CancelorderPage');
}
cancelorderDetails()
{
console.log(this.cancelorderde.value);
}
}
In this ts file, I have validated the IFSC Code but after that also the error is not coming but the user is not able to click on Submit Button.
I want that when the user enter the wrong input, it should the error to the user and when there is no error, user can click on submit button.
Any help is much appreciated.
Just Try This: It will work.
<ion-content padding>
<p class="newp11">Order Number: {{orderpa}}</p>
<h2 class="myformh2">Fill Your Account Detail's</h2>
<form [formGroup]="cancelorderde" (ngSubmit)="cancelorderDetails()">
<ion-list>
<ion-item class="newitem2">
<ion-input placeholder="IFSC Code*" type="text" formControlName="ifsc_code" required></ion-input>
</ion-item>
<p *ngIf="cancelorderde.controls['ifsc_code'].errors && cancelorderde.controls['ifsc_code'].dirty && cancelorderde.get('ifsc_code').touched" class="danger" padding>IFSC Code Is Not Valid</p>
<div>
<button [disabled]="!cancelorderde.valid" ion-button type="submit" class="newbtn11" color="primary" block>Cancel Order</button>
</div>
</ion-list>
</form>
</ion-content>
Move p tag out of the item tag. It will show the error according to the question asked and solved your problem.

Ionic4 ngSubmit is not firing on submit

Using Ionic4 for the first time and struggling with ngSubmit not triggering the respective method in the login page. Although its always successfully hitting the LoginPage constructor and AuthService constructor. All the respective modules have been imported and there are no console errors too. What am i doing wrong ?
login.page.html:
<ion-header>
<ion-toolbar>
<ion-title>
Login
</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<form (ngSubmit)="login()" [formGroup]="loginForm">
<ion-grid>
<ion-row>
<ion-col>
<ion-item>
<ion-input type="text" placeholder="Email" formControlName="email" style="width:50%;"></ion-input>
</ion-item>
</ion-col>
</ion-row>
<ion-row>
<ion-col col-3>
<ion-item>
<ion-input type="password" placeholder="Password" formControlName="password" style="width:50%;"></ion-input>
</ion-item>
</ion-col>
</ion-row>
</ion-grid>
<div padding-horizontal>
<div class="form-error">{{loginError}}</div>
</div>
<ion-grid>
<ion-row>
<ion-col>
<ion-button type="submit" [disabled]="!loginForm.valid" color="primary">Log in</ion-button>
Forgot password?
</ion-col>
</ion-row>
<ion-row>
<ion-col>
<ion-button icon-left block clear (click)="loginWithGoogle()" color="secondary">
<ion-icon name="logo-google"></ion-icon>
Log in with Google
</ion-button>
<ion-button icon-left block clear (click)="signup()" color="primary">
<ion-icon name="person-add"></ion-icon>
Sign up
</ion-button>
</ion-col>
</ion-row>
</ion-grid>
</form>
</ion-content>
login.page.ts:
import { Component, OnInit } from '#angular/core';
import { AuthService } from '../common/services/auth.service';
import { FormGroup, FormBuilder, Validators } from '#angular/forms';
import { Router } from '#angular/router';
#Component({
selector: 'app-login',
templateUrl: './login.page.html',
styleUrls: ['./login.page.scss'],
})
export class LoginPage implements OnInit {
loginForm: FormGroup;
loginError: string;
constructor(private auth:AuthService,
private router:Router,
private fb: FormBuilder)
{
this.loginForm = this.fb.group({
email: ['', Validators.compose([Validators.required, Validators.email])],
password: ['', Validators.compose([Validators.required, Validators.minLength(6)])]
});
}
ngOnInit() {}
login() {
alert('login');
let data = this.loginForm.value;
if (!data.email) {
return;
}
let credentials = {
email: data.email,
password: data.password
};
this.auth.signInWithEmail(credentials)
.then(
() => this.router.navigate(['/home']),
error => this.loginError = error.message
);
}
}
login.module.ts:
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { FormsModule,ReactiveFormsModule } from '#angular/forms';
import { Routes, RouterModule } from '#angular/router';
import { IonicModule } from '#ionic/angular';
import { LoginPage } from './login.page';
const routes: Routes = [
{
path: '',
component: LoginPage
}
];
#NgModule({
imports: [
CommonModule,
FormsModule,
ReactiveFormsModule,
IonicModule,
RouterModule.forChild(routes),
],
entryComponents: [LoginPage],
declarations: [LoginPage]
})
export class LoginPageModule {}
auth.service.ts:
import { Injectable } from '#angular/core';
import { AngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase/app';
import AuthProvider = firebase.auth.AuthProvider;
#Injectable({
providedIn: 'root'
})
export class AuthService {
private user: firebase.User;
constructor(public afAuth: AngularFireAuth) {
afAuth.authState.subscribe(user => {
this.user = user;
});
}
signInWithEmail(credentials) {
console.log('Sign in with email');
return this.afAuth.auth.signInWithEmailAndPassword(credentials.email,
credentials.password);
}
}
ngSubmit is reloading the complete page and hence its hitting only login constructor but not the respective method. Removed (ngSubmit) on <form>, type="submit" on <ion-button>, added (click)="login()" event to <ion-button>. It started working.

Form Validation after updating Ionic

I had a Form Validation working but after updating Ionic doesn't work. Here's my code:
form.html
<ion-header>
<ion-navbar>
<ion-title>
Authorization Form Demo
</ion-title>
</ion-navbar>
</ion-header>
<ion-content class="home" padding>
<form [ngFormModel]="authForm" (ngSubmit)="onSubmit(authForm.value)">
<ion-item [class.error]="!username.valid && username.touched">
<ion-label floating>Username</ion-label>
<ion-input type="text" value="" [ngFormControl]="username"></ion-input>
</ion-item>
<div *ngIf="username.hasError('required') && username.touched"
class="error-box">* Username is required!</div>
<div *ngIf="username.hasError('minlength') && username.touched"
class="error-box">* Minimum username length is 8!</div>
<div *ngIf="username.hasError('checkFirstCharacterValidator') && username.touched"
class="error-box">* Username cant't start with number!</div>
<ion-item [class.error]="!password.valid && password.touched">
<ion-label floating>Password</ion-label>
<ion-input type="text" value="" [ngFormControl]="password" ></ion-input>
</ion-item>
<div *ngIf="password.hasError('required') && password.touched"
class="error-box">* Password is required</div>
<div *ngIf="password.hasError('minlength') && password.touched"
class="error-box">* Minimum password length is 8!</div>
<div *ngIf="password.hasError('checkFirstCharacterValidator') && password.touched"
class="error-box">* Password cant't start with number!</div>
<br/><br/>
<button type="submit" class="custom-button" [disabled]="!authForm.valid" block>Submit</button>
</form>
</ion-content>
form.ts
import {Component} from '#angular/core';
import {NavController} from 'ionic-angular';
import {FORM_DIRECTIVES, FormBuilder, ControlGroup, Validators, AbstractControl} from '#angular/common';
import {CustomValidators} from '../validators/CustomValidators';
#Component({
templateUrl: 'build/pages/form/form.html',
directives: [FORM_DIRECTIVES]
})
export class FormPage {
authForm: ControlGroup;
username: AbstractControl;
password: AbstractControl;
constructor(private navController: NavController, private fb: FormBuilder) {
this.authForm = fb.group({
'username': ['', Validators.compose([Validators.required, Validators.minLength(8), CustomValidators.checkFirstCharacterValidator])],
'password': ['', Validators.compose([Validators.required, Validators.minLength(8), CustomValidators.checkFirstCharacterValidator])]
});
this.username = this.authForm.controls['username'];
this.password = this.authForm.controls['password'];
}
onSubmit(value: string): void {
if(this.authForm.valid) {
console.log('Submitted value: ', value);
}
}
}
CustomValidators.ts
import { Control, ControlGroup } from "#angular/common";
interface ValidationResult {
[key: string]: boolean;
}
export class CustomValidators {
public static checkFirstCharacterValidator(control: Control): ValidationResult {
var valid = /^\d/.test(control.value);
if (valid) {
return {checkFirstCharacterValidator: true};
}
return null;
}
}
Somebody know what changes I need to do for working fine?
Thanks in advance.
Best regards.
Beta11 of Ionic2 has made breaking changes in form handling, you can read more here.
form.ts edit two lines to look like this:
import {FORM_DIRECTIVES, FormBuilder, FormGroup, Validators, AbstractControl} from '#angular/forms';
authForm: FormGroup;
You need to import new forms component from #angular/forms not the deprecated one #angular/common and change deprecated ControlGroup to FormGroup
In form.html edit one line to:
<form [formGroup]="authForm" (ngSubmit)="onSubmit(authForm.value)" novalidate>
Change deprecated ngFormModel to formGroup and consider adding novalidate attribute to your form.
To make your custom validator work you also have to change two lines in CustomValidators.ts but I didnt have time to read all changes and never used custom validators before. So this may require more work
import { FormControl, FormGroup } from "#angular/forms";
public static checkFirstCharacterValidator(control: FormControl): ValidationResult {