File

src/app/profile/personal-details-edit/personal-details-edit.page.ts

Implements

OnInit

Metadata

Index

Properties
Methods
Accessors

Constructor

constructor(profileService: ProfileService, commonUtilService: CommonUtilService, fb: FormBuilder, events: Events, headerService: AppHeaderService, router: Router, location: Location, changeDetectionRef: ChangeDetectorRef)
Parameters :
Name Type Optional
profileService ProfileService No
commonUtilService CommonUtilService No
fb FormBuilder No
events Events No
headerService AppHeaderService No
router Router No
location Location No
changeDetectionRef ChangeDetectorRef No

Methods

enableSubmitButton
enableSubmitButton()
Returns : void
Async getDistrict
getDistrict(parentId: string, resetDistrictFlag?: boolean)
Parameters :
Name Type Optional
parentId string No
resetDistrictFlag boolean Yes
Returns : any
Async getStates
getStates()
Returns : any
initializeForm
initializeForm()

Initializes form with default values or empty values

Returns : void
ionViewWillEnter
ionViewWillEnter()

Ionic life cycle event - Fires every time page visits

Returns : void
ngOnInit
ngOnInit()
Returns : void
onSubmit
onSubmit()

It will validate the forms and internally call submit method

Returns : void
Async submitForm
submitForm()

It makes an update API call.

Returns : any
validateName
validateName()

It will validate the name field.

Returns : any

Properties

Private _districtList
Type : []
Default value : []
Private _stateList
Type : []
Default value : []
btnColor
Type : string
Default value : '#8FC4FF'
categories
Type : []
Default value : []
Public commonUtilService
Type : CommonUtilService
disableSubmitFlag
Default value : false
districtOptions
Type : object
Default value : { title: this.commonUtilService.translateMessage('DISTRICT').toLocaleUpperCase(), cssClass: 'select-box' }
editData
Default value : true
frameworkId
Type : string
profile
Type : any
profileEditForm
Type : FormGroup
showOnlyMandatoryFields
Default value : true
stateOptions
Type : object
Default value : { title: this.commonUtilService.translateMessage('STATE').toLocaleUpperCase(), cssClass: 'select-box' }

Accessors

stateList
getstateList()
setstateList(v)
Parameters :
Name Optional
v No
Returns : void
districtList
getdistrictList()
setdistrictList(v)
Parameters :
Name Optional
v No
Returns : void
import { Router } from '@angular/router';
import { AppHeaderService, CommonUtilService } from '../../../services';
import { Component, Inject, OnInit, ChangeDetectorRef } from '@angular/core';
import { Events } from '@app/util/events';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Location as loc } from '../../app.constant';
import { LocationSearchCriteria, ProfileService } from 'sunbird-sdk';
import { Location } from '@angular/common';

@Component({
  selector: 'app-personal-details-edit',
  templateUrl: './personal-details-edit.page.html',
  styleUrls: ['./personal-details-edit.page.scss'],
})
export class PersonalDetailsEditPage implements OnInit {

  private _stateList = [];
  private _districtList = [];

  get stateList() {
    return this._stateList;
  }

  set stateList(v) {
    this._stateList = v;
    this.changeDetectionRef.detectChanges();
  }

  get districtList() {
    return this._districtList;
  }

  set districtList(v) {
    this._districtList = v;
    this.changeDetectionRef.detectChanges();
  }

  profile: any;
  profileEditForm: FormGroup;
  frameworkId: string;
  categories = [];
  btnColor = '#8FC4FF';
  showOnlyMandatoryFields = true;
  editData = true;

  /* Custom styles for the select box popup */
  stateOptions = {
    title: this.commonUtilService.translateMessage('STATE').toLocaleUpperCase(),
    cssClass: 'select-box'
  };
  districtOptions = {
    title: this.commonUtilService.translateMessage('DISTRICT').toLocaleUpperCase(),
    cssClass: 'select-box'
  };
  disableSubmitFlag = false;

  constructor(
    @Inject('PROFILE_SERVICE') private profileService: ProfileService,
    public commonUtilService: CommonUtilService,
    private fb: FormBuilder,
    private events: Events,
    private headerService: AppHeaderService,
    private router: Router,
    private location: Location,
    private changeDetectionRef: ChangeDetectorRef
  ) {
    if (this.router.getCurrentNavigation().extras.state) {
      this.profile = this.router.getCurrentNavigation().extras.state.profile;
    }
  }

  ngOnInit() {
    this.getStates();
    this.initializeForm();
  }

  /**
   * Ionic life cycle event - Fires every time page visits
   */
  ionViewWillEnter() {
    this.headerService.showHeaderWithBackButton();
  }

  /**
   * Initializes form with default values or empty values
   */

  initializeForm() {
    let profileName = this.profile.firstName;
    const userState = [];
    const userDistrict = [];
    if (this.profile.lastName) {
      profileName = this.profile.firstName + this.profile.lastName;
    }
    if (this.profile && this.profile.userLocations && this.profile.userLocations.length) {
      for (let i = 0, len = this.profile.userLocations.length; i < len; i++) {
        if (this.profile.userLocations[i].type === 'state') {
          userState.push(this.profile.userLocations[i].id);
          this.getDistrict(this.profile.userLocations[i].id);
        } else {
          userDistrict.push(this.profile.userLocations[i].id);
        }
      }
    }
    this.profileEditForm = this.fb.group({
      states: userState || [],
      districts: userDistrict || [],
      name: [profileName.trim(), Validators.required],
    });
    this.enableSubmitButton();
  }

  async getStates() {
    let loader = await this.commonUtilService.getLoader();
    await loader.present();
    const req: LocationSearchCriteria = {
      filters: {
        type: loc.TYPE_STATE
      }
    };
    this.profileService.searchLocation(req).subscribe(async (success) => {
      const locations = success;
      loader.dismiss();
      loader = undefined;
      if (locations && Object.keys(locations).length) {
        this.stateList = locations;
      } else {
        this.commonUtilService.showToast(this.commonUtilService.translateMessage('NO_DATA_FOUND'));
      }
    }, async (error) => {
      if (loader) {
        loader.dismiss();
        loader = undefined;
      }
    });
  }

  async getDistrict(parentId: string, resetDistrictFlag?: boolean) {
    let loader = await this.commonUtilService.getLoader();
    await loader.present();
    const req: LocationSearchCriteria = {
      filters: {
        type: loc.TYPE_DISTRICT,
        parentId
      }
    };
    this.profileService.searchLocation(req).subscribe(async (success) => {
      const districtsTemp = success;
      loader.dismiss();
      loader = undefined;
      if (districtsTemp && Object.keys(districtsTemp).length) {
        this.districtList = districtsTemp;
      } else {
        this.districtList = [];
        this.commonUtilService.showToast(this.commonUtilService.translateMessage('NO_DATA_FOUND'));
      }
      if (resetDistrictFlag) {
        this.profileEditForm.patchValue({
          districts: []
        });
      }
      this.enableSubmitButton();
    }, async (error) => {
      if (loader) {
        loader.dismiss();
        loader = undefined;
      }
    });
  }

  /**
   * It will validate the forms and internally call submit method
   */
  onSubmit() {
    const formVal = this.profileEditForm.getRawValue();
    if (!formVal.name.trim().length) {
      this.commonUtilService.showToast(this.commonUtilService.translateMessage('ERROR_NAME_INVALID'), false, 'redErrorToast');
    } else {
      this.submitForm();
    }
  }

  enableSubmitButton() {
    const formValues = this.profileEditForm.value;
    if ((formValues.states && formValues.states.length && formValues.districts && formValues.districts.length) ||
      (formValues.states && !formValues.states.length && formValues.districts && !formValues.districts.length)) {
      this.disableSubmitFlag = false;
    } else if (formValues.states && formValues.states.length && formValues.districts && !formValues.districts.length) {
      this.disableSubmitFlag = true;
    }
  }

  /**
   * It makes an update API call.
   */
  async submitForm() {
    let loader = await this.commonUtilService.getLoader();
    await loader.present();
    const req = {
      userId: this.profile.userId,
      lastName: ' ',
      firstName: this.validateName(),
      locationCodes: []
    };

    if (this.profileEditForm.value.states && this.profileEditForm.value.states.length) {
      const tempState = this.stateList.find(state => state.id === this.profileEditForm.value.states);
      req.locationCodes.push(tempState.code);
    }
    if (this.profileEditForm.value.districts && this.profileEditForm.value.districts.length) {
      const tempDistrict = this.districtList.find(district => district.id === this.profileEditForm.value.districts);
      if (tempDistrict) {
        req.locationCodes.push(tempDistrict.code);
      }
    }

    this.profileService.updateServerProfile(req).toPromise()
      .then(async () => {
        await loader.dismiss();
        loader = undefined;
        this.commonUtilService.showToast(this.commonUtilService.translateMessage('PROFILE_UPDATE_SUCCESS'));
        this.events.publish('loggedInProfile:update', req);
        this.location.back();
      }).catch(async () => {
        if (loader) {
          await loader.dismiss();
          loader = undefined;
        }
        this.commonUtilService.showToast(this.commonUtilService.translateMessage('PROFILE_UPDATE_FAILED'));
      });
  }

  /**
   *  It will validate the name field.
   */
  validateName() {
    const name = this.profileEditForm.getRawValue().name;
    return name.trim();
  }

}
<ion-content class="ion-padding-vertical">
  <form [formGroup]="profileEditForm">
    <ion-item>
      <ion-label position="stacked" class="label-font">
        {{'NAME' | translate}}
        <ion-text>
          <span class="error">&nbsp;*</span>
        </ion-text>
        <div class="error"
          *ngIf="profileEditForm.controls.name.dirty && profileEditForm.controls.name.errors?.required">
          {{'ERROR_NAME_INVALID' | translate}}</div>
      </ion-label>
      <ion-input class="form-control" #name formControlName="name" placeholder="{{ 'NAME_HINT' | translate }}"
       dir="{{commonUtilService.getAppDirection()}}"></ion-input>
    </ion-item>
    <ion-item>
      <ion-label position="stacked" class="label-font">{{'STATE' | translate}}</ion-label>
      <ion-select  [disabled]="!stateList.length" formControlName="states" #stateSelect multiple="false"
      placeholder="{{ (stateList.length ? 'STATE_OPTION_TEXT':'NO_DATA_FOUND') | translate }}" okText="{{'BTN_SUBMIT' | translate}}"
        cancelText="{{'CANCEL' | translate}}" (ionChange)="getDistrict(stateSelect.value, true);">
        <ion-select-option *ngFor="let state of stateList" class="ion-text-capitalize" value="{{state?.id}}">{{state?.name}}
        </ion-select-option>
      </ion-select>
    </ion-item>
    <ion-item>
      <ion-label position="stacked" class="label-font">{{'DISTRICT' | translate}}</ion-label>
      <ion-select [disabled]="!districtList.length" formControlName="districts" #districtSelect multiple="false"
        [disabled]="!profileEditForm.value.states" placeholder="{{ (districtList.length ? 'DISTRICT_OPTION_TEXT':'NO_DATA_FOUND') | translate }}"
        okText="{{'BTN_SUBMIT' | translate}}" cancelText="{{'CANCEL' | translate}}"
        (ionChange)="enableSubmitButton()">
        <ion-select-option *ngFor="let district of districtList" value="{{district?.id}}">{{district?.name}}
        </ion-select-option>
      </ion-select>
    </ion-item>
  </form>
</ion-content>

<ion-footer>
  <ion-row class="padding-12">
    <ion-col size-md="10" offset-md="1">
      <ion-button expand="block" [ngStyle]="{'background-color': btnColor}" 
      [disabled]="profileEditForm.invalid || (!profileEditForm.invalid && disableSubmitFlag)"
        (click)="onSubmit()">{{'SAVE'| translate}}</ion-button>
    </ion-col>
  </ion-row>
</ion-footer>

./personal-details-edit.page.scss

@import "src/assets/styles/_variables.scss";
@import "src/assets/styles/_custom-mixins.scss";
:host {
    .label-font {
       font-weight: 600 !important;
        color: map-get($colors, dark_gray) !important;
        font-size: 0.875rem !important;
    }
    .select-text {
      //font-size: 1.2rem !important;
    }
    .select-text:first-letter {
        text-transform: capitalize;
    }
  
    .custom-footer-background .toolbar-background-ios, .custom-footer-background .toolbar-background-md{
      background: unset !important;
    }
    .padding-12 {
        padding: 12px !important;
    }
    .item-select-disabled {
        .label-md {
            color: map-get($colors, medium_gray);
            opacity: 1;
        }
    }
    .popover-alert .popover-content {
      margin: 0;
      width: 100% !important;
      max-height: 70% !important;
      box-shadow: unset;
      position: fixed;
      left: 0 !important;
      top: unset !important;
      bottom: 0;
      transform-origin: bottom -100% !important;
      transform: translateY(0) !important;
    }
    
    .popover-alert ion-backdrop {
      background-color: map-get($colors, black) !important;
      opacity: 0.4 !important;
    }
    
    .popover-alert .close-button{
        background-color: map-get($colors, white);
        box-shadow: unset;
        color: map-get($colors, black);
        float: right;
        ion-icon {
          padding: 0;
          margin-top: 10px;
        }
    }
  
    .popover-alert .alert-header{
      margin-left: 2px 
    }
    .popover-alert .col-2{
      padding: 0 ;
      margin-left: 20px ;
    } 
  
    .popover-alert .alert-button {
      margin-top: 26px;
      border-radius: 5px;
    }
  
    .popover-alert .alert-header-content{
      padding: 0;
      margin-left: -7px;
    }
  
    .popover-alert .alert-header-padding {
      margin-top: -11px;
  
    }
    .popover-alert ion-content{
      padding: 15px;
    }
    .popover-alert .alert-content-body{
      color: darkgrey;
    }

    .label-stacked.sc-ion-label-md-h{
      transform: translate3d(0,0,0) scale(1);
    }

    ion-item {
      @include padding(16px, null, null, null);
    }
  }
  
Legend
Html element
Component
Html element with directive

results matching ""

    No results matching ""