I have written the following code:
test.html
<ion-header>
<ion-navbar>
<ion-title>faq</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<div >
<h2 >Demo Form: Sku</h2>
<form [formGroup]="myForm" (ngSubmit)="onSubmit(myForm.value)">
<ion-item>
<ion-label floating>SKU</ion-label>
<ion-input type="text" id="skuInput" name="sku" [formControl]="myForm.controls['sku']"></ion-input>
</ion-item>
<ion-card >
<ion-card-header >
<ion-label >Q1. Test Question</ion-label>
</ion-card-header>
<ion-list radio-group name="question" [formControl]="myForm.controls['question']">
<ion-item>
<ion-label>Yes</ion-label>
<ion-radio value="true"></ion-radio>
</ion-item>
<ion-item>
<ion-label>No</ion-label>
<ion-radio value="false"></ion-radio>
</ion-item>
</ion-list>
</ion-card>
<button ion-button type="submit" round>
Submit
</button>
</form>
</div>
</ion-content>
test.ts
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { FormControl, FormBuilder, FormGroup, Validators, AbstractControl} from '@angular/forms';
@Component({
templateUrl: 'test.html',
})
export class TestPage {
myForm : FormGroup;
sku: AbstractControl;
constructor(public nav: NavController,
public fb : FormBuilder) {
this.myForm = fb.group({
'sku': ['', Validators.compose([Validators.required,this.skuValidator])],
'question' : ['', Validators.required]
});
this.sku = this.myForm.controls['sku'];
}
onSubmit(value : string): void {
if(!this.myForm.valid){
if(this.myForm.controls['sku'].hasError('required')){
alert('SKU is mendatory.');
return;
}
if(this.myForm.controls['sku'].hasError('invalidSku')){
alert('SKU is invalid.');
return;
}
if(this.myForm.controls['question'].hasError('required')){
alert('Question is mendatory.');
return;
}
}
console.log('you submitted value:', value);
this.myForm = this.fb.group({
'sku': ['', Validators.compose([Validators.required,this.skuValidator])],
'question' : ['', Validators.required]
});
}
skuValidator(control: FormControl): { [s: string]: boolean } {
if (!control.value.match(/^123/)) {
alert('Inside skuValidator');
console.log('value of this :: ' , this);
return {invalidSku: true};
}
}
}
In side the function skuValidator, I am printing the value of âthisâ but it is coming as undefined. Due to this, i am not able to validate the form against the value which I have to read from the service. Is there something I am doing wrong or it is by default designed this way?