Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
HTML:
<div [formGroup]="userFormGroup">
<div class="row" formGroupName="userGroup">
<div class="userinfo col-md-6">
<mat-form-field [floatLabel]="'always'" hidden> // hide this input field
<input matInput class="domainPrefixValidate" formControlName="prefixField" (blur)="checkPrefix()" placeholder="DOMAIN PREFIX" required>
<span matSuffix>.onmicrosoft.com</span>
</mat-form-field>
<mat-form-field [floatLabel]="'always'">
<input matInput class="userNameValidate" formControlName="userNameField" placeholder="USER NAME" requried>
<mat-icon matSuffix class="usernameicon" placement="top" ngbTooltip="Default login is admin">info</mat-icon>
</mat-form-field>
<mat-form-field [floatLabel]="'always'">
<input matInput class="firstNameValidate" formControlName="firstNameField" placeholder="FIRST NAME" required>
</mat-form-field>
<mat-form-field [floatLabel]="'always'">
<input matInput class="lastNameValidate" formControlName="lastNameField" placeholder="LAST NAME" required>
</mat-form-field>
<mat-form-field [floatLabel]="'always'">
<input matInput class="companyNameValidate" formControlName="companyNameField" placeholder="COMPANY NAME" required>
</mat-form-field>
<mat-form-field [floatLabel]="'always'">
<input matInput class="emailValidate" formControlName="emailField" placeholder="EMAIL" required>
</mat-form-field>
</div>
<div class="userinfo col-md-6">
<mat-form-field [floatLabel]="'always'">
<input matInput class="addressLine1Validate" formControlName="addressLine1Field" placeholder="ADDRESS LINE 1" required>
</mat-form-field>
<mat-form-field [floatLabel]="'always'">
<input matInput class="addressLine2Validate" formControlName="addressLine2Field" placeholder="ADDRESS LINE 2">
</mat-form-field>
<mat-form-field [floatLabel]="'always'">
<input matInput class="addressLine3Validate" formControlName="addressLine3Field" placeholder="ADDRESS LINE 3">
</mat-form-field>
<mat-form-field [floatLabel]="'always'">
<input matInput class="suburbValidate" [matAutocomplete]="autoSuburb" formControlName="suburbField" placeholder="SUBURB" required>
<mat-autocomplete #autoSuburb="matAutocomplete">
<mat-option *ngFor="let option of filteredSub | async" [value]="option?.suburb" (click)="chooseAutoComplete(option)">
{{option?.suburb+", "+option?.state+", "+option?.postcode}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
<mat-form-field [floatLabel]="'always'">
<mat-select class="stateValidate" placeholder="State" formControlName="stateField" required>
<mat-option value="{{state}}" *ngFor="let state of stateList">{{state}}</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field [floatLabel]="'always'">
<input matInput class="postcodeValidate" maxlength="4" (keypress)="_keyPress($event)" formControlName="postcodeField" [matAutocomplete]="autoPostcode" placeholder="POST CODE" required>
<mat-autocomplete #autoPostcode="matAutocomplete">
<mat-option *ngFor="let option of filteredPostCode | async" [value]="option?.postcode" (click)="chooseAutoComplete(option)">
{{option?.suburb+", "+option?.state+", "+option?.postcode}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
<mat-form-field [floatLabel]="'always'">
<input matInput (keypress)="_keyPress($event)" class="phoneValidate" formControlName="phoneField" placeholder="PHONE" required>
</mat-form-field>
</div>
</div>
</div>
component:
userFormGroup: FormGroup;
private formBuilder: FormBuilder,
filteredPostCode: Observable<SuburbList[]>;
filteredSub: Observable<SuburbList[]>;
ngOnInit() {
this.filteredPostCode = this.userFormGroup.get('userGroup.postcodeField').valueChanges
.pipe(
startWith(''),
map(value => this._filterPostcode(value))
);
this.filteredSub = this.userFormGroup.get('userGroup.suburbField').valueChanges
.pipe(
startWith(''),
map(value => this._filterSuburb(value))
);
}
getUserGroup(): FormGroup {
return this.formBuilder.group({
prefixField: new FormControl("", Validators.compose([Validators.required, Validators.pattern('^[a-zA-Z0-9]+$')])),
firstNameField: new FormControl("", Validators.compose([Validators.required])),
lastNameField: new FormControl("", Validators.compose([Validators.required])),
emailField: new FormControl("", Validators.compose([Validators.required, Validators.email])),
userNameField: new FormControl({ value: "admin", disabled: true }, Validators.required), // disable this field
companyNameField: new FormControl("", Validators.compose([Validators.required])),
addressLine1Field: new FormControl("", Validators.compose([Validators.required])),
addressLine2Field: new FormControl(""),
addressLine3Field: new FormControl(""),
suburbField: new FormControl("", Validators.compose([Validators.required])),
stateField: new FormControl("", Validators.compose([Validators.required])),
postcodeField: new FormControl("", Validators.compose([Validators.required])),
phoneField: new FormControl("", Validators.compose([Validators.required]))
});
}
chooseAutoComplete(option: SuburbList): void {
this.userFormGroup.get('userGroup.postcodeField').setValue(option.postcode);
this.userFormGroup.get('userGroup.stateField').setValue(option.state);
this.userFormGroup.get('userGroup.suburbField').setValue(option.suburb);
}
private _filterPostcode(value: string): SuburbList[] {
if (value && value.length > 2) {
let filterValue = value.toLowerCase();
return this.geoData.filter(option => option.state && option.postcode.toLowerCase().includes(filterValue));
}
}
private _filterSuburb(value: string): SuburbList[] {
if (value && value.length > 2) {
let filterValue = value.toLowerCase();
return this.geoData.filter(option => option.state && option.suburb.toLowerCase().includes(filterValue));
}
}
this.userFormGroup.getRawValue() // could get value from disabled input field and hidden field
HTML:
<div [formGroup]="addressFormGroup">
<div formGroupName="addressGroup">
<mat-form-field [floatLabel]="'always'">
<input matInput formControlName="companyName" placeholder="Company Name" (blur)="isNotValidField('addressGroup.companyName', account_validation_messages.companyName)"/>
</mat-form-field>
<mat-checkbox [(ngModel)]="collectTheOrder" formControlName="collectTheOrder" style="display: block;margin-left: 18px;">
I will collect this order
</mat-checkbox>
</div>
</div>
model:
export interface SelectedAddress{
companyName: string;
}
Component:
addressFormGroup: FormGroup;
account_validation_messages: any = {
'companyName': [
{ class: 'companyNameValidate', message: 'Please enter company name' }
],
'attnOrRef': [
{ class: 'attnOrRefValidate', message: 'Please enter attn or ref' }
],
'address': [
{ class: 'addressValidate', message: 'Please enter address' }
],
'suburb': [
{ class: 'suburbValidate', message: 'Please enter suburb' }
],
'state': [
{ class: 'stateValidate', message: 'Please enter state' }
],
'postCode': [
{ class: 'postcodeValidate', message: 'Please enter postcode' }
],
'phone': [
{ class: 'phoneValidate', message: 'Please enter phone' }
]
}
account_maintain_validation_messages: any = {
'companyName': [
{ class: 'companyNameMaintainValidate', message: 'Please enter company name' }
],
'attnOrRef': [
{ class: 'attnOrRefMaintainValidate', message: 'Please enter attn or ref' }
],
'address': [
{ class: 'addressMaintainValidate', message: 'Please enter address' }
],
'suburb': [
{ class: 'suburbMaintainValidate', message: 'Please enter suburb' }
],
'state': [
{ class: 'stateMaintainValidate', message: 'Please enter state' }
],
'postCode': [
{ class: 'postcodeMaintainValidate', message: 'Please enter postcode' }
],
'phone': [
{ class: 'phoneMaintainValidate', message: 'Please enter phone' }
]
}
constructor(private formBuilder: FormBuilder) {
this.addressFormGroup = this.formBuilder.group({
addressGroup: this.getAddressGroup(),
collectTheOrder: new FormControl(false, [Validators.required]),
cartId: new FormControl(0)
});
}
ngOnInit() {
*** model property name equal to formControlName, then could set model to form ***
this.addressFormGroup.get('addressGroup').setValue(this.selectedAddress);
}
getAddressGroup(): FormGroup {
return this.formBuilder.group({
companyName: new FormControl('', Validators.compose([
UsernameValidator.validUsername,
Validators.maxLength(25),
Validators.minLength(5),
Validators.pattern('^(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9]+$'),
Validators.required
])),
maintainNaType: new FormControl(0),
});
}
isNotValidField(path: string, validation: any): void {
if(!this.userFormGroup.get(path).valid) or if(!this.userFormGroup.get(path).hasError("required")){
this.commonService.showValidator("." + validation[0].class, validation[0].message, "right", "error");
}
}
submit form:
if (this.addressFormGroup.get('addressGroup').valid) {
}else{
this.isNotValidField('addressGroup.companyName', this.account_validation_messages.companyName);
}
** cartId is an example to save value in formGroup when cartId is not set in the form
** set value
level 1:
this.addressFormGroup.controls['cartId'].setValue(this.cartId);
level 2:
this.addressFormGroup.get('addressGroup').get('maintainNaType').setValue('I');
** get value
this.addressFormGroup.controls['cartId'].value
this.addressFormGroup.get('addressGroup').get('maintainNaType').value
** set value to grandchild control (property is in the form)
this.addressFormGroup.get('addressGroup.companyName').setValue(this.startDate);
** get value(property is in the form)
this.addressFormGroup.get('addressGroup.companyName').value
** disable input box
Example:
form = new FormGroup({
first: new FormControl({value: 'Nancy', disabled: true}, Validators.required),
last: new FormControl('Drew', Validators.required)
});
if (this.userFormGroup.get("userGroup").valid) {
//could get value from disabled input field and hidden field
this.checkOutService.CreateCSPTenant(JSON.stringify(this.userFormGroup.get("userGroup").getRawValue())).subscribe((res: TenantResponse) => {
console.info(res);
},
(error: any) => {
console.error(error);
this.commonService.showError(".saveuser", error.responseMessage, "right");
this.ngProgress.done();
});
}
in the backend
use code below to parse string and get value
var formData = JsonConvert.DeserializeObject<Dictionary<string, string>>(data);
string companyName = formData["companyName"];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.