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
- Template
- Class
- 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
- Interpolation / String Interpolation (one-way data binding)
- Property Binding (one-way data binding)
- Event Binding (one-way data binding)
- 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'; }
- 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.
- 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.
- 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>
- [value]=”username” – Binds the expression username to the input element’s value property
- (input)=”expression” – Is a declarative way of binding an expression to the input element’s input event (yes there’s such event)
- username = $event.target.value – The expression that gets executed when the input event is fired
- $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
- Get a watch from list
- Check whether item has been changed
- If there is no change in item then
- No Action taken, move to next item in watch list
Second Cycle
- Get a watch from list
- Check whether item has been changed
- If there is Change in an item
- 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.
- The value could be decided at runtime by passing as paremeter
- The Button could be used multiple times with different text