Tuesday, 26 November 2019

Angular Template Syntax and NgClass & NgStyle Directives

<!-- Native Class and Style Attributes -->
<input class="is-danger my-button" style="border: none; color: blue">
<!-- Angular class and style Bindings -->
<input [class.is-danger]="booleanProp" [style.border]="borderProp">
<!-- ngClass -->
<input [ngClass]="{'is-danger': booleanProp, 'myButton': true}">
<input [ngClass]="isDangerButton">
<!-- ngStyle -->
<input [ngStyle]="{'border': borderProp, 'color': colorProp}">
<input [ngStyle]="hasColorBorder">
<!--
booleanProp, borderProp, etc...
would be properties from our
Typescript class
-->

NgClass



NgClass can receive input via inline declarations, or a property/method from our TypeScript class. This can make the syntax feel more convoluted than it really is. Ultimately, NgClass can take the following as input:
  • A space-delimited String [ngClass]="is-info is-item has-border"
  • An Array of Strings [ngClass]="['is-info', 'is-item', 'has-border'"]
  • An Object [ngClass]="{'is-info': true, 'is-item': true}
All of the above examples are inline and could be replaced with a Typescript property/method as long as the expression returns valid input:
export class MyComponentClass {
myStringProperty = "is-info is-item has-border";
myArrayProperty = ['is-info', 'is-item', 'has-border'];
myObjectProperty = {'is-info': true, 'is-item': true};
}
  • [ngClass]="myStringProperty"
  • [ngClass]="myArrayProperty"
  • [ngClass]="myObjectProperty"


Key Points

  • We can pass a Typescript property/method or write an expression inline to our NgClass Directive
  • NgClass can take a String, Array of Strings, or Object Expression as input.
  • Under the hood, NgClass is adding/removing classes via Renderer2 addClass() and removeClass()
  • NgClass appends, it does not overwrite.



NgStyle

NgClass and NgStyle share a significant amount of functionality and behavior. The key difference is:
  • NgStyle takes a key-value pair object as input.
  • NgStyle applies styles and not classes.
  • NgStyle will overwrite styles defined by the native style attribute.

Syntax

NgStyle takes a key-value pair object, where the key is a CSS style. An optional suffix can be added to the key, making keys such as this viable:
[ngStyle]="{font-size.px: 16}" Instead of [ngStyle]="{font-size: 16px}"
Similar to NgClass, NgStyle can be passed input inline or use a Typescript property/method. [ngStyle]="myObjectExpressionProperty"

Key Takeaways

  • NgStyle can accept a key-value pair as input, where the key is a valid CSS Style
  • NgStyle can be passed input via inline or a Typescript property or method
  • NgStyle under the hood utilizes Angular’s Renderer2 to invoke setStyle() and removeStyle()
  • NgStyle will overwrite existing styles on the element.

Friday, 20 September 2019

new Html A Tag Types Link rel Types For SEO

rel="sponsored": Use the sponsored attribute to identify links on your site that were created as part of advertisements, sponsorships or other compensation agreements.

rel="ugc": UGC stands for User Generated Content, and the ugc attribute value is recommended for links within user generated content, such as comments and forum posts.

rel="nofollow": Use this attribute for cases where you want to link to a page but don’t want to imply any type of endorsement, including passing along ranking credit to another page.

Wednesday, 10 July 2019

Group by created_at date_trunc to the day level in postgres

Using date_trunc to reduce time precision
date_trunc is one of many date/time functions built into Postgres, but certainly scores high in its bang for the buck for me.
date_trunc truncates timestamps to a certain level of precision, such as a specific hour, second, day, week, year, or so on.
As an example, let's create a very simple orders table which stores solely the time an order is created:
CREATE TABLE orders (created_at timestamp);

INSERT INTO orders VALUES
  ('2019-01-01 04:05:33'),
  ('2019-01-01 09:05:51'),
  ('2019-01-03 02:55:14'),
  ('2019-01-08 14:12:07');
Now, we can use date_trunc upon created_at to, say, group and count orders by day or week:
SELECT date_trunc('day', created_at) AS day,
       COUNT(created_at) FROM orders
       GROUP BY day
       ORDER BY day;
day                 | count
----------------------------
2019-01-01T00:0 ... | 2
2019-01-08T00:0 ... | 1
2019-01-03T00:0 ... | 1
This basic example shows that if we group by created_at truncated to the day level, we can count how many orders there were on each unique day.

Sunday, 12 May 2019

How to add a column in every table of a database?

do $$
declare
    selectrow record;
begin
for selectrow in
    select
      'ALTER TABLE '|| T.mytable || ' ADD COLUMN IF NOT EXISTS insert_by bigint' as script
   from
      (
        select tablename as mytable from  pg_tables where schemaname  ='public' --your schema name here
      ) t
loop
execute selectrow.script;
end loop;
end;
$$;




PostgreSQL: How to add a column in every table of a database?

Sunday, 7 April 2019

Number validation in Angular 6 and 7


numberValidation.ts

import { FormGroup, FormControl, Validators,AbstractControl,ValidatorFn   } from '@angular/forms';

export function numberValidation(prms:any = {}): ValidatorFn {
    return (control: FormControl): {[key:string]: any} => {
      let val: number = control.value;

      if(isNaN(val) || /\D/.test(val.toString())) {

        return {"number": true};
      } else if(!isNaN(prms.min) && !isNaN(prms.max)) {

        return val < prms.min || val > prms.max ? {"number": true} : null;
      } else if(!isNaN(prms.min)) {

        return val < prms.min ? {"number": true} : null;
      } else if(!isNaN(prms.max)) {

        return val > prms.max ? {"number": true} : null;
      } else {

        return null;
      }
    };
  }




in Your Component  import numberValidation File 

import { numberValidation } from '../../common/validation/numberValidation';


Angular 6 Check only Number 

      VPNRemotePort: new FormControl('', [numberValidation()])

Angular 6 Validation Check only Min Number Validation

     VPNRemotePort: new FormControl('', [numberValidation({min:1})])

Angular 6 Validation Check only Max Number Validation

     VPNRemotePort: new FormControl('', [numberValidation({max:1})])

Angular 6 Validation Check only Min and MAx Number Validation

     VPNRemotePort: new FormControl('', [numberValidation({min:1,max:65535})])

Component Html Use Example  key name is number 

<div *ngIf="VPNRemotePort.invalid && VPNRemotePort.dirty" class="text-danger padding-2">
                              <div *ngIf="VPNRemotePort.errors.number">
                                {{getVPNRemotePortInvalidErrorMsg}}
                              </div>
                            </div>



You Can Also Write a  Validation function in Same Component 


VpnRemotePortValidator(portValue: String): ValidatorFn {
  return (control: AbstractControl): {[key: string]: any} | null => {
        let vpnRemotePort = parseInt(control.value);
        if (isNaN(vpnRemotePort) === true){
          return {'invalidPort':true};
        } else if (vpnRemotePort < 1 || vpnRemotePort > 65000){
          return {'invalidPort':true};
        } else {
          return null;
        }
  };
}

Use Example 

 VPNRemotePort: new FormControl('', [this.VpnRemotePortValidator])])


Component Html Use Example key name is invalidPort
<div *ngIf="VPNRemotePort.invalid && VPNRemotePort.dirty" class="text-danger padding-2">
                              <div *ngIf="VPNRemotePort.errors.invalidPort">
                                {{getVPNRemotePortInvalidErrorMsg}}
                              </div>
                            </div>



Custom Validation in Angular 6

Custom Validation function in  Same Component Angular 6 and Angular 7

Custom Number Min Max Validation in Angular 6




Friday, 29 March 2019

load dynamic script in angular 6

import { Component, ViewEncapsulation, OnInit, ElementRef, NgModule, NgZone, ViewChild, AfterViewInit } from '@angular/core';
         
declare var google: any; 

  ngAfterViewInit(): void {
    let googleApiKey = 'AIzaSyB4a';
    let googleMapsUrl = 'https://maps.googleapis.com/maps/api/js?key=' + googleApiKey + '&libraries=places'; // replace by your API key
    this.addMapsScript(googleMapsUrl);
  }


  addMapsScript(googleMapsUrl: string) {
    if (!document.querySelectorAll(`[src="${googleMapsUrl}"]`).length) {
      document.body.appendChild(Object.assign(
        document.createElement('script'), {
          type: 'text/javascript',
          src: googleMapsUrl,
          onload: () => this.createGoogleSearchBox()
        }));
    } else {
      this.createGoogleSearchBox();
    }
  }

createGoogleSearchBox() {
    let updateSitesLocationEl = document.getElementById('txtUpdateSitesLocation');
    let updateSitesLocation = new google.maps.places.SearchBox(updateSitesLocationEl);
    updateSitesLocation.addListener('places_changed', function() {
      let searchBoxValue = self.getValueFromGoogleSearchBox(updateSitesLocation);
      self.updateSitesLocationData['location'] = searchBoxValue.location;
    });
  }

First import AfterViewInit from angular core

create google variable 

in ngAfterViewInit   set google api key and google library url

call a addMapsScript  function in ngAfterViewInit 


After a script onload event call you other google map function s




Load google map script in angular 6

dynamic load google script in angular 6 ,7

Tuesday, 26 March 2019

Router in Angular 6,7,8


interface Route {
  path?: string
  pathMatch?: string
  matcher?: UrlMatcher
  component?: Type<any>
  redirectTo?: string
  outlet?: string
  canActivate?: any[]
  canActivateChild?: any[]
  canDeactivate?: any[]
  canLoad?: any[]
  data?: Data
  resolve?: ResolveData
  children?: Routes
  loadChildren?: LoadChildren
  runGuardsAndResolvers?: RunGuardsAndResolvers
}

1.      path - It uses the route matcher DSL
2.      pathMatch - It uses to specifies the matching strategy
3.      matcher - It uses to defines a custom strategy for path matching
4.      component - It is a component type
5.      redirectTo - It is the URL fragment and it will replace the current matched segment
6.      outlet - It is the name of the outlet the component should be placed into
7.      canActivate  - It is an array of DI tokens  and used to handle the CanActivate handlers
8.      canActivateChild - It is an array of DI tokens and used to handle the CanActivateChild handlers
9.      canDeactivate - It is an array of DI tokens and used to handle the CanDeactivate handlers
10.  canLoad - It is an array of DI tokens and used to handle the CanLoad handlers
11.  data - It is additional data provided to the component by using the ActivatedRoute
12.  resolve - It is a map of DI tokens used to look up data resolvers
13.  runGuardsAndResolvers - It is defined when guards and resolvers will be run and by default, they run only when the matrix parameters of the route change.
14.  children - it is an array of child route definitions
15.  loadChildren - It is a reference to lazily loaded child routes.



Angular router has own library package - @angular/router.
import {Routes, RouterModule,}  from '@angular/router';

The basic concept of Angular Router and It allows you to -
1.      Redirect a URL to another URL
2.      Resolve data before a page is displayed
3.      Run scripts when a page is activated or deactivated
4.      Lazy load parts of our application

The router supports both styles with two LocationStrategy providers -
1.      PathLocationStrategy— this is the default style.
2.      HashLocationStrategy— adds the route path to the hash (#) in the browser’s URL.