Skip to content

Instantly share code, notes, and snippets.

@rajaramtt
Last active September 12, 2019 18:20
Show Gist options
  • Save rajaramtt/d79edc926b54c4879b65c6462b2fc867 to your computer and use it in GitHub Desktop.
Save rajaramtt/d79edc926b54c4879b65c6462b2fc867 to your computer and use it in GitHub Desktop.
angular imp notes

Angular Preloading Strategy

Preloading in Angular means loading the Lazy loaded Modules in the background asynchronously, while user is interacting with the app. This will help boost up the loading time of the app

const app_routes: Routes = [
 { path: 'auth', loadChildren: './modules/auth/auth.module#AuthModule' },
 { path: 'reset-password', redirectTo: 'auth/reset-password', pathMatch: 'full' },
 { path: '**', redirectTo: '/auth/404' }, 
];

@NgModule({
imports: [RouterModule.forRoot(app_routes, { preloadingStrategy: PreloadAllModules })],
exports: [RouterModule]
})

https://www.tektutorialshub.com/angular/angular-preloading-strategy/

app-settings.config.ts

export const appSettings = {

  countries: [
    { value: '91', name: 'IND (+91)' },
  ],
};

Map Example:

 import { tap, map } from 'rxjs/operators';
 import { Observable, BehaviorSubject, ReplaySubject, pipe, Subject } from 'rxjs';
 import { of as observableOf } from 'rxjs';
 
  private isAuthenticatedSubject = new BehaviorSubject<boolean>(false);
  public isAuthenticated = this.isAuthenticatedSubject.asObservable();

  login(credentials: JSON): Observable<User> {   
    return this.http.post(`${environment.loginService}`, credentials, { withCredentials: true })
      .pipe(
        map(response => {          
          const storage = sessionStorage;
          const beforeencryption = response['userDetails'];
          -----------------------
          ----------------------
          ----------------------
          return beforeencryption;
        }));
  }
  
  
  
  userInfo(): Observable<User> {
    const savedCredentials = JSON.parse(sessionStorage.getItem(credentialsKey));
      ---------------------
      ---------------------

    return observableOf(savedCredentials['userDetails']);
  }
  
     -------------------
     -------------------
 
    test(user: User) {

    this.isAuthenticatedSubject.next(true);
  }

@Input() and @Output()

 <app-patient-card [patientInputData]="caregiverPatientsList" [disableActions]="disableActions" [isCallHide]="true" (patientOutputData)="careGiverPatientOutputData($event)"></app-patient-card>
  careGiverPatientOutputData(outputData): void {
   this.disableActions = 'none';
   switch (outputData.actionType) {
     case 'delete':
       -------outputData.patient.id------
       break;
        -------------
     default:
       this.router.navigateByUrl(`/admin/caregivers`);
   }
 }

/************Child ************/

 @Input() patientInputData = new Array<Patient>();
 @Output() patientOutputData = new EventEmitter<object>();
 @Input() isCallHide: false;
 @Input() disableActions: string;
 
   patientActions(patient: Patient, actionType: string) {
   this.patientOutputData.emit({
     patient: patient,
     actionType: actionType
   });
 }
 
 
<mat-icon class="card-icon" (click)="patientActions(patient, 'edit')">edit</mat-icon>
-------------------
-------------------
-------------------

Confirm password

    this.resetForm = this.formBuilder.group({
     password: ['', [Validators.required, Validators.minLength(6), Validators.maxLength(20)]],
     confirmPassword: ['', [Validators.required]],
     typeofdevice: ['web'],
     tokenId: [tokenID],
     languagePreference: [this.preferredLang]
   },
     {
       validator: MustMatch('password', 'confirmPassword')
     });
     
     import { FormGroup } from '@angular/forms';

export function MustMatch(controlName: string, matchingControlName: string) {
   return (formGroup: FormGroup) => {
       const control = formGroup.controls[controlName];
       const matchingControl = formGroup.controls[matchingControlName];
       if (matchingControl.errors && !matchingControl.errors.mustMatch) {
           return;
       }
       if (control.value !== matchingControl.value) {
           matchingControl.setErrors({ mustMatch: true });
       } else {
           matchingControl.setErrors(null);
       }
   };
}

     

MatDialog

....................


@NgModule({
declarations: [.......,  PlayVideoComponent ],
imports: [
  ....................
],
entryComponents: [
  PlayVideoComponent
],
providers: [AuthGuard]
})
export class CMSModule { }
import { MatDialog } from '@angular/material';
import { PlayVideoComponent } from '../play-video/play-video.component';

 playVideo(name: string): void {

   const confirmDialog = this.dialog.open(PlayVideoComponent, {
     width: '500px',
     data: { name },
     disableClose: true
   });

 }
  
 play-video.component
 
import { Component, OnInit, Inject } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA, MatDialog } from '@angular/material';
import { environment } from '../../../../environments/environment';

@Component({
selector: 'app-play-video',
templateUrl: './play-video.component.html',
styleUrls: ['./play-video.component.scss']
})
export class PlayVideoComponent implements OnInit {

environment: any;
heplVideoURL = environment.helpVideoURL;

constructor(public dialog: MatDialog,
  @Inject(MAT_DIALOG_DATA) public data: any,
) { }

ngOnInit() {
}

closeDialog() {
  this.dialog.closeAll();
}


}
 

  deletePrescription(id: string): void {

  const confirmDialog = this.dialog.open(DeleteDialogComponent, {
    width: '500px',
    disableClose: true
  });
  confirmDialog.afterClosed().subscribe(confirmationResponse => {
    if (confirmationResponse === appToaster.deleteConfirmationMessage) {
      this.testttService.deletePrescription(id).subscribe((response) => {
        if (response.status === 'success') {
        this.toasterService.pop('success', appToaster.testtttttttttt);
        this.ngOnInit();
        } else {
           this.toasterService.pop('error', response.message);
        }
      });
    }
  });
}



<button mat-flat-button color="warn" matDialogClose="close">{{'labelsAndPlaceholders.commonLabels.cancel' | translate}}</button>

bypassSecurityTrustResourceUrl

import {DomSanitizer } from '@angular/platform-browser';

constructor(public sanitizer: DomSanitizer) { }

this.videoURL = this.sanitizer.bypassSecurityTrustResourceUrl(res['iframeURL']);

filter

  filterRecords(event): void {
   const val = event.target.value.toLowerCase();
   this.prescriptions = this.filteredRecordsList.filter( (d) => {
     return d.problem.toLowerCase().indexOf(val) !== -1 ||
       d.solution.toLowerCase().indexOf(val) !== -1 ||
       !val;
   });

 }
 
 Use .map(), .reduce(), and .filter()
https://medium.com/poka-techblog/simplify-your-javascript-use-map-reduce-and-filter-bd02c593cc2d

Reactive Form

notificationForm: FormGroup;

---------------------------
---------------------------

 this.notificationForm = this.formBuilder.group({
      notificationList: this.formBuilder.array([
      ])
    });
    
    
 get notificationList() {
    return this.notificationForm.get('notificationList') as FormArray;
  }
  
  
  
    initNotificationListForm(): void {
    this.notificationList.push(
      this.formBuilder.group({
        id: [],
        expectedTime: [null, [Validators.required, Validators.pattern('^[1-9][0-9]{0,2}?$')]],
        notificationType: [null, [Validators.required]],
        notificationValue: [null, [Validators.required]],
        countryCode: [],
        userId: []
      })
    );
  }
  
  
   removeForm(i: number): void {
    this.notificationList.removeAt(i);
  }
  
  
 <div [formGroup]="notificationForm">
 <div formGroupName="notificationList">
  <div [formGroupName]="i">
  <input matInput type="number" formControlName="expectedTime"" min="1" required>
  <mat-error [class.is-required]="notificationForm['controls'].notificationList['controls'][i]['controls'].expectedTime.invalid && (notificationForm['controls'].notificationList['controls'][i]['controls'].expectedTime.dirty || notificationForm['controls'].notificationList['controls'][i]['controls'].expectedTime.touched )">

IF else template

<mat-hint *ngIf="tessttt;else napcomment">
------------
------------
 </mat-hint>
 
 <ng-template #napcomment>
    <mat-hint>
      ------------
      ------------
     </mat-hint>
   </ng-template>

Class

 <mat-icon [class.data-available-icon]="testVall != null" class="notify-icon">notifications</mat-icon>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment