Template Variable to Interact with Child Components in Angular 2+

I have already discussed in my last couple of blogs to interact Components using @Input and @Output. Here I am going to explain about Template Variable to interact with Child Components. By using this Template reference variable you can access public properties and methods of a child component and also to bind data to a child component.
Template Reference Variable allow you to specify a variable name on a component and you can access any public property or methods on that component using that variable.

In order to demonstrate I have a product card component which is my child component placed inside the  ProductListComponent(parent component) to list some products. You can see I have added a template reference variable named #productReference on this child component

So over here in our ProductCardComponent will just a create a method and property to access from the ProductListComponent

Now you can access this property and method from the ProductListComponent

Load Components Dynamically at runtime in Angular 4

Angular Version I have used – 4.2.0
Here I am going to explain how to load dynamic components at runtime. By using angular ComponentFactoryResolver you can load components dynamically. In the below example I am loading a Image widgets in to tile(nothing but a container div to load the widget at runtime). You can use this to in order to implement the need of $compile in Angular 1.0

WidgetHostDirective
In order to load a dynamic component you need a directive that you can apply to ng-template which will helps to load the components at run time. This directive injects ViewContainerRef to gain access to the view container of the element that will host the dynamically added component.

import { Directive, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[widget-host]',
})
export class DashboardTileWidgetHostDirective {
constructor(public viewContainerRef: ViewContainerRef) {
}
}

DashboardTileComponent
This component accepts an input which is coming from a parent components or you can load from your service based on your implementation. This component is doing the major role to resolve the components at runtime. In this method you can also see a method named renderComponent() which ultimately loads the component name from a service and resolve with ComponentFactoryResolver and finally setting data to the dynamic component.
import { Component, Input, OnInit, AfterViewInit, ViewChild, ComponentFactoryResolver, OnDestroy } from '@angular/core';
import { DashboardTileWidgetHostDirective } from './DashbardWidgetHost.Directive';
import { TileModel } from './Tile.Model';
import { WidgetComponentService } from "./WidgetComponent.Service";
@Component({
selector: 'dashboard-tile',
templateUrl: 'app/tile/DashboardTile.Template.html'
})
export class DashboardTileComponent implements OnInit {
@Input() tile: any;
@ViewChild(DashboardTileWidgetHostDirective) widgetHost: DashboardTileWidgetHostDirective;
constructor(private _componentFactoryResolver: ComponentFactoryResolver,private widgetComponentService:WidgetComponentService) {

}
ngOnInit() {

}
ngAfterViewInit() {
this.renderComponents();
}
renderComponents() {
let component=this.widgetComponentService.getComponent(this.tile.componentName);
let componentFactory = this._componentFactoryResolver.resolveComponentFactory(component);
let viewContainerRef = this.widgetHost.viewContainerRef;
let componentRef = viewContainerRef.createComponent(componentFactory);
(componentRef.instance).data = this.tile;

}
}
export interface TileModel {
data: any;
}

You can see I have applied the directive we have created before to the ng-template
DashboardTileComponent Template

WidgetComponentService
This is a simple angular service which just the component name that we want to load at runtime

Entry Component
To ensure that the compiler still generates a factory, add dynamically loaded components to the NgModule’s entryComponents array

Communicating with parent component from child component in Angular Js2

In my last blog I have explained about @Input decorator to pass data from parent component to the child component. @Output is on other hand used in response to some event within a child component to receive some information for the parent component through some events. If you are not read my previous blog , I would suggest you to read the same. I have used the same example here also.

Child Component
Let’s talk about the child component first. You can see I have a simple method named productCardClick() which I am calling when clicking on the button. It’s pretty straight forward.

Modifying the child component
Next I am going to pass some data to the parent through the same productCardClick() method in the child component. In order to do that first you have to add a new property of type EventEmitter and emit the data you want to pass in to the parent component through this property like below .

Parent Component
Let’s go the parent component named ProductListComponent


In the parent component (ProductListComponent) you can see I have receiver method named onProductCardClickHandled(data:any) with a parameter to receive the data from the child component and I am calling this receiver method with a parameter via the @Output decorated property onProductCardClick inside the child component. Now when you click the button you will receive the child component data in to the parent component

Communicating with child components from parent component in Angular Js2

Breaking our application in to multiple components makes our application more organized and maintainable. Here I am going to explain how to pass data from parent component to child component.

Parent Component
Here is our ProductListComponent , which is the parent component with a productObject declared which I am going to pass in to the child component.

This is my productList html for displaying the product object. You can see I am calling the product-card component(Child Component) from this productListComponent

Child Component

Child Component template

In this component I have declared a variable named product decorated with @Input , which tell to the child component that , you will get an input product from the parent component(ProductListComponent). For passing the input data from the parent component to the child component you have to add an attribute match with property decorated with the @Input inside a square bracket like below and the value here I am passing will be the productObject from the ProductListComponent

defineProperty method in Javascript

defineProperty is a method on Object which allow you to configure the properties to meet some criterias.
Here is a simple example with an employee object with two properties firstName & lastName and append the two properties by overriding the toString method on the object.
You will get Output as : Jameel Moideen

I am going to change the same code by using defineProperty on the object

The first parameter is the name of the object and then second parameter is name of the property we are adding , in our case it’s toString and then the last parameter is json object which have a value going to be a function and three parameters writable,enumerable and configurable.Right now I just declared everything as true.

If u run the example you will get Output as : Jameel Moideen

Let’s understand why we need the three properties such as writable,enumerable and configurable.
writable
One of the very annoying part of the javascript is , if you change the toString property to something else for example

if run this again , everything gets breaks
Let’s change writable to false. If run the same again you will get the correct output as ‘Jameel Moideen’ . This property will prevent overwrite this property later.
enumerable
if you print all the keys inside the object , you can see all the properties including toString.
console.log(Object.keys(employee));
if you set enumerable to false , you can hide toString property from everybody else. If run this again you will get firstName,lastName
configurable

if someone later redefined the object on later for example enumerable to true and run it. You can see toString property came again.


we no need this behavior , so you can restrict this by set configurable to false.

Set HTTP Cache Expiration in Angular JS and Typescript

Create an Interceptor for every service calls

angular.module('app').factory("cacheInterceptor", ["$cacheFactory", function ($cacheFactory) {
 var httpTtlCache = {};
 return {
 request: function (config) {
 var expirationTime;
 if (config.expiration) {
 expirationTime = config.expiration;
 delete config.expiration;
 if (new Date().getTime() - (httpTtlCache[config.url] || 0) > expirationTime) {
 $cacheFactory.get("$http").remove(config.url);
 httpTtlCache[config.url] = new Date().getTime();
 }
 }
 return config;
 }
 };
}]);

Push the interceptor through config

angular.module('app', []).config(['$httpProvider', function ($httpProvider) {
 $httpProvider.interceptors.push('cacheInterceptor');
}]);

Pass the expiration when you call your httpservice

  var expirationTime = 60 * 60 * 1000;
            $http.get(url, { expiration: expirationTime,cache:true }).then(function (response) {
               
            });

Row Level Security In SQL Server 2016

By using Row Level Security(RLS) you can filter and block access to individual rows within a table based on some custom logic that you write inside a predicate function.
A predicate function is an ordinary inline table-valued function(TVF) which SQL Server executes against every DML operation on the table.Your predicate function typically compare the current user context with some column value in each and return yes or no if that row is accessible.You can apply the predicate function to the table by creating a security policy and SQL Server immediately filters in the case of
select or blocks in the case of insert,update,delete.You can easily turn on and off at any time for any table.There are two types of predicates

  1. Filter Predicates
  2. Block Predicate

Filter Predicate
You can apply filter predicates on any select, update ot delete statement so that rows deemed inaccessible to the user are not processed by the select , update or delete operation.

Block Predicate
This predicate is more like triggers, preventing the user from inserting , updating or deleting rows that violate the rules of the predicate function. there are variations for predicate function

AFTER INSERT, AFTER UPDATE
Can’t insert or update rows to values that would violate the predicate
BEFORE UPDATE, BEFORE DELETE
Can’t update or delete rows that violates the predicate

Security Predicate Functions
Security Predicate Functions are table valued function (TVF) which you write in T-SQL. This TVF must be a schema bound which means that all object references, tables or other functions must be fully qualified by schema name even if it’s default dbo schema.

Example

For showing the demo I have created a sample Sales table where with orders where we want each salesperson to access only the orders in the table they are assigned.Means each person should have private access to their owns orders and none of the sales person can access to other salesperson orders.So we will grant read only access to their orders and only one admin user has read and write access to all the rows in a table.

Create a user, this could be any database user whether that user is a SQL server login or windows authentication login.Here I am created the users without any login

Create an sec schema

You can see username parameter which map to the username column when we create the security policy below. In the above function you can see Table return WITH SCHEMABINDING which is mandatory for predicate functions.

Let’s apply security policy on sales table for testing the predicate function created. for that I am running predicate function as User1

When I select the above predicate function you can see a permission error . The SELECT permission was denied on the object ‘fn_securitypredicate’, database ‘SampleDB’, schema ‘sec’. which is expected because  we will not allow the normal users to execute the table valued function selecting from directly. For testing i am giving a temporary grant select permission to the User1.

Execute the select statement again.Now you can see predicate function return 1

I am again executing the function by passing as User2 and you can see that no result is returned meaning that rows with User2 in the sales Username column are inaccessible to queries executed by User1

Let’s test the Table Valued Function for the Admin User. For that I am going to REVERT to default dbo user and removing the select permission from the TVF that we added temporarily before

which will return 1

Let’s create a new Security policy with Filter Predicate we have created before

Let’s select the records from sales table and you can see no records return because Now it’s run under default dbo user.
SELECT * FROM Sales

Let’s execute as User1 and you can see that three records are showing corresponding to the user1
EXECUTE AS USER=’User1′
Select * from Sales

You can download the source from here