Cross-Origin Resource Sharing (CORS)
The browser’s same-origin policy blocks reading a resource from a different origin. This mechanism stops a malicious site from reading another site’s data. The same-origin policy tells the browser to block cross-origin requests. When you want to get a public resource from a different origin, the resource-providing server needs to tell the browser “This origin where the request is coming from can access my resource”. The browser remembers that and allows cross-origin resource sharing.

In angular when front end request origin is different the browser stops processing response from the server.

Request has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header
is present on the requested resource.

Same-Origin Policy

  1. The same-origin policy fights one of the most common cyber-attacks out there: cross-site request forgery.
  2. If you have logged into FB your info would be stored in Cookie and would be tagged along when the request is made every time
  3. Every time you re-visit the FB tab and click around the app, you don’t have to sign in again. Instead, the API will recognize the stored session cookie upon further HTTP requests.
    The only trouble is that the browser automatically includes any relevant cookies stored for a domain when another request is made to that exact domain.
  4. Say you clicked on a particularly trick popup ad, opening evil-site.com.The evil site also has the ability to send a request to FB.com/api. Since the request is going to the FB.com domain, the browser includes the relevant cookies. Evil-site sends the session cookie, and gains authenticated access to FB. Your account has been successfully hacked with a cross-site request forgery attack.
  5. At this point, browser will step in and prevent the malicious code from making an API request like this. It will stop evil-site and say “Blocked by the same-origin policy.

How Browser works underhood?

  1. The browser checks for the request origins of the web application and the Server origins response match
  2. The origin is the combination of the protocol, host, and port.
          For example, in https://www.FB.com, 
    	   the protocol is https://, 
    	   the host is www.FB.com, and 
    	   the hidden port number is 5400 (the port number typically used for https).
    
  3. To conduct the same-origin check, the browser accompanies all requests with a special request header
    that sends the domain information to receiving server
  4. For example, for an app running on localhost:3000, the special request format looks like this:
    Origin: http://localhost:3000
    

    Reacting to this special request, the server sends back a response header. This header contains an Access-Control-Allow-Origin key,
    to specify which origins can access the server’s resources. The key will have one of two values:

    One: the server can be really strict, and specify that only one origin can access it:
    Access-Control-Allow-Origin: http://localhost:3000

    Two: the server can let the gates go wide open, and specify the wildcard value to allow all domains to access its resources:
    Access-Control-Allow-Origin: *

  5. Once the browser receives this header information back, it compares the frontend domain with the Access-Control-Allow-Origin
    value from the server. If the frontend domain does not match the value, the browser raises the red flag and blocks the API
    request with the CORS policy error.

The above solution works for development. How about in production.

To address such issues, the proxy is used between client and server.

Request from Client -> Proxy Server -> Server 
Respose from Server -> Proxy Server(appends origin) -> Client

Now what the proxy does is it appends the s Access-Control-Allow-Origin: * in the header before the response is sent to the client browser

How to Delete duplicate Rows from Table

In the below table studId 1,6 and 9 is repeated which should be deleted.

studId studentName age
1 Mugil 35
2 Vinu 36
3 Viju 42
4 Mani 35
5 Madhu 36
6 Mugil 35
7 Venu 37
8 Banu 34
9 Mugil 35

Below query wont work on MySQL but the format doesn’t change. When you take Max only last occurrence of row would be taken and others would be excluded.

DELETE FROM tblStudents TS
 WHERE TS.studId NOT IN (SELECT MAX(TSS.studId)
                            FROM tblStudents TSS
                        GROUP BY TSS.studentName, TSS.age)c

The same could be done using MIN function.

SELECT TS.* FROM tblStudents TS
 WHERE TS.studId NOT IN (SELECT MIN(TSS.studId)
                           FROM tblStudents TSS
                          GROUP BY TSS.studentName, TSS.age)                        

Output

studId studentName age
6 Mugil 35
9 Mugil 35

1.What Is an Angular Component?
An Angular application is a tree of Angular components.The component contains the data & user interaction logic that defines how the View looks and behaves. A view in Angular refers to a template (HTML).Components are like the basic building block in an Angular application.Components are defined using the @component decorator. A component has a selector, template, style and other properties, using which it specifies the metadata required to process the component. Angular components are a subset of directives. Unlike directives, components always have a template and only one component can be instantiated per an element in a template.

Components consist of three main building block

  1. Template
  2. Class
  3. MetaData

2.Angularjs vs Angular
Angularjs and Angular should be treated as two different frameworks. Here are few comparisons as below

>

AngularJS Angular
Controllers WebComponents
AngularJS is written in JavaScript.

Angular uses Microsoft’s TypeScript language, which is a superset of ECMAScript 6 (ES6). This has the combined advantages of the TypeScript features, like type declarations, and the benefits of ES6, like iterators and lambdas.
AngularJS is based on model-view-controller(MVC) Design and MVVM(Model-view-view-model) by two way data binding .In AngularJS the MVC pattern is implemented in JavaScript and HTML. The view is defined in HTML, while the model and controller are implemented in JavaScript. The controller accepts input, converts it into commands and sends the commands to the model and the view Angular 2 is more of component based architecture. You can assume everything as component like directives, services and so on. While directives and services are actually for the support of base components, they are also defined in similar fashion. A base component contains of dependencies, a view details and class declaration which may be considered as controller. So a well defined component consist of individual set of MVC architecture.Angular 2, controllers and $scope were replaced by components and directives. Components are directives with a template. They deal with a view of the application and logic on the page.
HTML markup is the View, Controller is the Controller & the Service (when it used to retrieve data) is the model. template is the View, class is the Controller & the Service (when it used to retrieve data) is the model.
To bind an image/property or an event with AngularJS, you have to remember the right ng directive. Angular focuses on “( )” for event binding and “[ ]” for property binding.
No Mobile Support Angular 2 and 4 both feature mobile support.
2-way binding, AngularJS reduced the development effort and time. However, by creating more processing on the client side, page load was taking considerable time. Angular implements unidirectional tree-based change detection and uses Hierarchical Dependency Injection system. This significantly boosts performance for the framework.
two-way data binding in Angular 2 is supported using the event and the property binding. We can use ngModel directive to use two-way data binding.

3.What are Directives
Directives are something that introduce new syntax / markup. They are markers on the DOM element which provides some special behavior to DOM elements and tells AngularJS’s HTML compiler to attach.

There are three kinds of directives in an Angular 2 application.
Components
Angular Component also refers to a directive with a template which deals with View of the Application and also contains the business logic. It is very useful to divide your Application into smaller parts. In other words, we can say that Components are directives that are always associated with the template directly.

Structural directives
Structural directives are able to change the behavior of DOM by adding and removing DOM elements. The directive NgFor, NgSwitch, and NgIf is the best example of structural directives.

Attribute directives
Attribute directives are able to change the behavior of DOM. The directive NgStyle is an example of Attribute directives which are used to change styles elements at the same time.

4.Difference between Component and Directive
Directives
Directives add behaviour to an existing DOM element or an existing component instance. One example use case for a directive would be to log a click on an element.

import {Directive} from '@angular/core';

@Directive({
    selector: "[logOnClick]",
    hostListeners: {
        'click': 'onClick()',
    },
})
class LogOnClick {
    constructor() {}
    onClick() { console.log('Element clicked!'); }
}
<button logOnClick>I log when clicked!</button>

Components
A component, rather than adding/modifying behaviour, actually creates its own view (hierarchy of DOM elements) with attached behaviour. An example use case for this might be a contact card component:

import {Component, View} from '@angular/core';

@Component({
  selector: 'contact-card',
  template: `
    <div>
      <h1>{{name}}</h1>
      <p>{{city}}</p>
    </div>
  `
})
class ContactCard {
  @Input() name: string
  @Input() city: string
  constructor() {}
}
<contact-card [name]="'foo'" [city]="'bar'"></contact-card>
Directive Component
They are used to create behavior to an existing DOM element. A component is a directive with a template and the @Component decorator is actually a @Directive decorator extended with template-oriented features. It used to shadow DOM to create encapsulates visual behavior. It is used to create UI widgets.
They help us to create re-usable components It helps us to break up our application in smaller component
We cannot create pipes using Attribute / Structural directive Pipes can be defined by component
We can define many directive per DOM element We can present only one component per DOM element
@directive keyword is used to define metadata @component keyword is used to define metadata

5.Directive Lifecycle

For the Directives there are three hooks provided for different event based on which we can take actions upon
ngOnChanges – It occurs when Angular sets data bound property. Here, we can get current and previous value of changed object. It is raised before the initialization event for directive.

ngOnInit – It occurs after Angular initializes the data-bound input properties.

ngDoCheck – It is raised every time when Angular detects any change.

ngOnDestroy – It is used for cleanup purposes and it is raised just before Angular destroys the directive. It is very much important in memory leak issues by un-subscribing observables and detaching event handlers.

6.What are Types of Databinding in Angular

  1. Interpolation / String Interpolation (one-way data binding)
  2. Property Binding (one-way data binding)
  3. Event Binding (one-way data binding)
  4. Two-Way Binding

7.What is Interpolation?
Interpolation(one-way data binding) allows you to define properties in a component class, and communicate these properties to and from the template.
nterpolation is a technique that allows the user to bind a value to a UI element.Interpolation binds the data one-way. This means that when value of the field bound using interpolation changes, it is updated in the page as well. It cannot change the value of the field. An object of the component class is used as data context for the template of the component. So the value to be bound on the view has to be assigned to a field in the component class.String Interpolation uses template expressions in double curly {{ }} braces to display data from the component, the special syntax {{ }}, also known as moustache syntax. The {{ }} contains JavaScript expression which can be run by Angular and the output will be inserted into the HTML.

          {{value}}  
Component----------->DOM

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'stockMarket';
}

app.component.html

<h1>
    Welcome to {{ title }}!
</h1>

8.What is Property Binding (one-way data binding)?
Property binding is used to bind values to the DOM properties of the HTML elements. Like interpolation, property binding is a one-way binding technique. Property bindings are evaluated on every browser event and any changes made to the objects in the event, are applied to the properties.There are 3 types of Property Binding

app.component.ts

import {Component} from '@angular/core';

@Component({
selector: 'my-app',
template:'
<h1>My First Angular App</h1>
<img [src]="imageUrl">
<img bind-src="imageUrl">'
})

export class AppComponent { 
imageUrl = 'http://codethataint.com/images/sample.jpg';
}
  1. Component property binding works within component element to bind parent component property into child component property. In the diagram the arrows and rectangles in red color are displaying the functionality related to component property binding.
  2. Element property binding works within HTML element and it binds a component property to a DOM property. In the diagram the arrows and rectangle in green color are displaying the functionality related to element property binding.
  3. Directive property binding works within HTML element with angular directives such as NgClass and NgStyle. In directive property binding a component property or any angular expression is bound to angular directive. In the diagram the arrows and rectangles in light blue color are displaying the functionality related to directive property binding.

9.What is Event Binding(one-way data binding)?
Event binding allows us to work in reverse from property binding. We can send information from the view, to the component class. Such information usually involves a click, hover or typing.

import {Component} from '@angular/core';

@Component({
selector: 'my-app',
template:'
<h1>My First Angular App</h1>
<img [src]="imageUrl" (click)='myMethod()'>
<img [src]="imageUrl" on-click='myMethod()'>'
})

myMethod() {
   console.log('Hey!');
}

10.What is Two way Binding?
Two-way data binding really just boils down to event binding and property binding.

<input [(ngModel)]="username">
<p>Hello {{username}}!</p>

The above code turns out to be

<input [value]="username" (input)="username = $event.target.value">
<p>Hello {{username}}!</p>
  1. [value]=”username” – Binds the expression username to the input element’s value property
  2. (input)=”expression” – Is a declarative way of binding an expression to the input element’s input event (yes there’s such event)
  3. username = $event.target.value – The expression that gets executed when the input event is fired
  4. $event – Is an expression exposed in event bindings by Angular, which has the value of the event’s payload

11.What is the Difference between One way Data Binding and Two Way Data Binding

One Way Data Binding Two Way Data Binding
In one-way data binding, the value of the Model is inserted into an HTML (DOM) element and there is no way to update the Model from the View. In two-way binding automatic synchronization of data happens between the Model and the View (whenever the Model changes it will be reflected in the View and vice-versa)
One way data Binding flow would be
(Model($scope) –> View)
Two way data Binding flow would be
(Model($scope) –> View and View –> Model($scope))
Angular 1 and Angular 2:

<h2 ng-bind="student.name"></h2>
<h2 [innerText]="student.name"></h2></pre>
Angular 1 and Angular 2:

<input ngModel="student.name"/>
<input [(ngModel)]="student.name"/></pre>

12.What is Dirty Checking?
Angular checks whether a value has changed in view and not yet synchronized across the app.Our Angular app keeps track of the values of the current watches. Angular walks down the $watch list, and, if the updated value has not changed from the old value, it continues down the list. If the value has changed, the app records the new value and continues down the $watch list.

Angular has a concept of ‘digest cycle’. You can consider it as a loop. In which Angular checks if there are any changes to all the variables watched by all the $scopes(internally $watch() and $apply() functions are getting bonded with each variable defined under $scope).So if you have $scope.myVar defined in your controller (that means this variable ‘myVar’ was marked for being watched) then you are explicitly telling Angular to monitor the changes on ‘myVar’ in each iteration of the loop. So when the value of ‘myVar’ changes, every time $watch() notices and execute $apply() to apply the changes in DOM.

How it Works
First Cycle

  1. Get a watch from list
  2. Check whether item has been changed
  3. If there is no change in item then
  4. No Action taken, move to next item in watch list

Second Cycle

  1. Get a watch from list
  2. Check whether item has been changed
  3. If there is Change in an item
  4. DOM needs to be updated, return to digest loop

14.What is difference between [ngClass] and [class]?
When multiple classes should potentially be added, the NgClass prefer NgClass. NgClass should receive an object with class names as keys and expressions that evaluate to true or false as values

<div [ngClass]="myClasses">
  ...
</div>
myClasses = {
  important: this.isImportant,
  inactive: !this.isActive,
  saved: this.isSaved,
  long: this.name.length > 6
}

If you want to apply a single class to DOM element rather than multiple classes go for [Class]

<div [class]="isGreen?'green':'cyan'">
  ...
</div>

The Other way of applying class is using Singular Version of Class Binding
.In this method either class style would be applied or it would be left without anystyle

<div [class.green]="expression()">
  ...
</div>

The expression is a function which returns true or false value.If true then green style would be applied or no style would be applied

15.What is difference between ngStyle and ngClass?
ng-style is used to interpolate javascript object into style attribute, not css class and And ng-class directive translates your object into class attribute.

[ngStyle]="{'font-size':24}"
[ngClass]="{'text-success':true}"

15.What is Service?

16.What is Provider?

17.What is difference between Factory vs Service vs Provider?

18.Difference between @Inject vs @Injectable

19.What are Reactive Forms

20.How Dependency Injection is done in Angular?

21.Difference between Subscribe, Transform, Map and Filter?

22.Navigator vs Router

23.What is Lazy Loading in Angular

24.What is Difference between Subscribe and Promise?

25.Lifecycle of Angular App

26.How to Create Custom Event in Angular?

27.What are different style Encapsulation in Angular?
ViewEncapsulation.Emulated – This is default, keep styles scoped to the components where they are added even though the styles are all added collected in the head of the page when components are loaded.
ViewEncapsulation.None – Uses global CSS without any encapsulation,When this value is specified, Angular simply adds the unmodified CSS styles to the head section of the HTML document and lets the browser figure out how to apply the styles using the normal CSS precedence rules.
ViewEncapsulation.Native – the browsers native implementation ensures the style scoping.If the browser doesn’t support shadow DOM natively, the web-components polyfills are required to shim the behavior.Check for browser support before enabling it. This is similar to ViewEncapsulation.Emulated but the polyfills are more expensive because of they polyfill lots of browser APIs even when most of them are never used.

The Native and None values should be used with caution. Browser support for the shadow DOM feature is so limited that using the Native option is sensible only if you are using a polyfill library that provides compatibility for other browsers.

The None option adds all the styles defined by components to the head section of the HTML document and lets the browser figure out how to apply them. This has the benefit of working in all browsers, but the results are unpredictable, and there is no isolation between the styles defined by different components.

28.What is View Projection?
Projection is useful when we want the user to decide the input of the Component something like carousel where the inputs could be image, text or page which doesnot have much to do with component logic.
Lets say we have a button text which needs to be decided by the parent component dynamically.In such case we will pass the text of button as parameter to selector of child component like one below

parent.component.ts

<app-parentcounter>Increment Counter From Parent</app-parentcounter>

child.component.ts

<button (click)="increaseCounter()">
  <ng-content></ng-content>
 </button>

ng-content in child tells its a argument which should be passed from parent component. There are two advantages of using ng-content.

  1. The value could be decided at runtime by passing as paremeter
  2. The Button could be used multiple times with different text