Sun. Dec 22nd, 2024
Angular

1. What is Angular Framework?

Angular is a TypeScript-based open-source front-end platform that makes it easy to build applications with in web/mobile/desktop. The major features of this framework such as declarative templates, dependency injection, end to end tooling, and many more other features are used to ease the development.

2. What are the key components of Angular?

Below are key components of Angular are:

Component: These are the basic building blocks of angular application to control HTML views.
Modules: An angular module is set of angular basic building blocks like component, directives, services etc. An application is divided into logical pieces and each piece of code is called as “module” which perform a single task.
Templates: This represent the views of an Angular application.
Services: It is used to create components which can be shared across the entire application.
Metadata: This can be used to add more data to an Angular class.

3. What are components?

Components are the most basic UI building block of an Angular app which formed a tree of Angular components. These components are subset of directives. Unlike directives, components always have a template and only one component can be instantiated per an element in a template. Let’s see a simple example of Angular component

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

@Component ({
selector: 'my-app',
template: <div> <h1>{{title}}</h1> <div>This is Angular component</div> </div>,
})

export class AppComponent {
title: string = 'Welcome to Angular component';
}

4. What are directives?

Directives add behaviour to an existing DOM element or an existing component instance.

import { Directive, ElementRef, Input } from ‘@angular/core’;

@Directive({ selector: ‘[highlightcss]’ })
export class HighlightDirective {
constructor(el: ElementRef) {
el.nativeElement.style.backgroundColor = ‘yellow’;
}
}

5. What is a module?

Modules are logical boundaries in your application and the application is divided into separate modules to separate the functionality of your application. Below app.module.ts root module declared with @NgModule decorator,

import { NgModule } from ‘@angular/core’;
import { BrowserModule } from ‘@angular/platform-browser’;
import { AppComponent } from ‘./app.component’;

@NgModule ({
imports: [ BrowserModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
The NgModule decorator has three options

The imports option is used to import other dependent modules. The BrowserModule is required by default for any web based angular application
The declarations option is used to define components in the respective module
The bootstrap option tells Angular which Component to bootstrap in the application

6. What are lifecycle hooks available?

Angular application goes through an entire set of processes or has a lifecycle right from its initiation to the end of the application.

Below are the description of each lifecycle method :

ngOnChanges: When the value of a data bound property changes, then this method is called.
ngOnInit: This is called whenever the initialization of the directive/component after Angular first displays the data-bound properties happens.
ngDoCheck: This is for the detection and to act on changes that Angular can’t or won’t detect on its own.
ngAfterContentInit: This is called in response after Angular projects external content into the component’s view.
ngAfterContentChecked: This is called in response after Angular checks the content projected into the component.
ngAfterViewInit: This is called in response after Angular initializes the component’s views and child views.
ngAfterViewChecked: This is called in response after Angular checks the component’s views and child views.
ngOnDestroy: This is the cleanup phase just before Angular destroys the directive/component.

7. What is a service?

A service is used when a common functionality needs to be provided to various modules. Services allow for greater separation of concerns for your application and better modularity by allowing you to extract common functionality out of components. Let’s create a repoService which can be used across components,

import { Injectable } from ‘@angular/core’;
import { Http } from ‘@angular/http’;

@Injectable() // The Injectable decorator is required for dependency injection to work
export class RepoService{
constructor(private http: Http){
}

fetchAll(){
return this.http.get(‘https://api.github.com/repositories’).map(res => res.json());
}
}
The above service uses Http service as a dependency.

8. What is dependency injection in Angular?

Dependency injection (DI), is an important application design pattern in which a class asks for dependencies from external sources rather than creating them itself. Angular comes with its own dependency injection framework for resolving dependencies( services or objects that a class needs to perform its function).So you can have your services depend on other services throughout your application.

9. What is a data binding?

Data binding is a core concept in Angular and allows to define communication between a component and the DOM, making it very easy to define interactive applications without worrying about pushing and pulling data. There are four forms of data binding(divided as 3 categories) which differ in the way the data is flowing.

From the Component to the DOM: Interpolation: {{ value }}: Adds the value of a property from the component
Name: {{ user.name }}
Address: {{ user.address }}
Property binding: [property]=”value”: The value is passed from the component to the specified property or simple HTML attribute


From the DOM to the Component: Event binding: (event)=”function”: When a specific DOM event happens (eg.: click, change, keyup), call the specified method in the component

Two-way binding: Two-way data binding: [(ngModel)]=”value”: Two-way data binding allows to have the data flow both ways. For example, in the below code snippet, both the email DOM input and component email property are in sync.

10. What is metadata?

Metadata is used to decorate a class so that it can configure the expected behavior of the class. The metadata is represented by decorators

Class decorators, e.g. @Component and @NgModule
import { NgModule, Component } from ‘@angular/core’;

@Component({
selector: ‘my-component’,
template: ‘

Class decorator’,
})
export class MyComponent {
constructor() {
console.log(‘Hey I am a component!’);
}
}

@NgModule({
imports: [],
declarations: [],
})
export class MyModule {
constructor() {
console.log(‘Hey I am a module!’);
}
}


Property decorators Used for properties inside classes, e.g. @Input and @Output
import { Component, Input } from ‘@angular/core’;

@Component({
selector: ‘my-component’,
template: ‘

Property decorator’
})

export class MyComponent {
@Input()
title: string;
}


Method decorators Used for methods inside classes, e.g. @HostListener
import { Component, HostListener } from ‘@angular/core’;

@Component({
selector: ‘my-component’,
template: ‘

Method decorator’
})
export class MyComponent {
@HostListener(‘click’, [‘$event’])
onHostClick(event: Event) {
// clicked, event available
}
}
Parameter decorators Used for parameters inside class constructors, e.g. @Inject
import { Component, Inject } from ‘@angular/core’;
import { MyService } from ‘./my-service’;

@Component({
selector: ‘my-component’,
template: ‘

Parameter decorator’
})
export class MyComponent {
constructor(@Inject(MyService) myService) {
console.log(myService); // MyService
}
}

11. What is interpolation?

Interpolation is a special syntax that Angular converts into property binding. It’s a convenient alternative to property binding. It is represented by double curly braces({{}}). The text between the braces is often the name of a component property. Angular replaces that name with the string value of the corresponding component property. Let’s take an example,

{{title}}

In the example above, Angular evaluates the title and url properties and fills in the blanks, first displaying a bold application title and then a URL.

12. What are template expressions?

A template expression produces a value similar to any Javascript expression. Angular executes the expression and assigns it to a property of a binding target; the target might be an HTML element, a component, or a directive. In the property binding, a template expression appears in quotes to the right of the = symbol as in [property]=”expression”. In interpolation syntax, the template expression is surrounded by double curly braces. For example, in the below interpolation, the template expression is {{username}},

{{username}}, welcome to Hello World

13. What are template statements?

A template statement responds to an event raised by a binding target such as an element, component, or directive. The template statements appear in quotes to the right of the = symbol like (event)=”statement”.

Let’s take an example of button click event’s statement

<button (click)=”editProfile()”>Edit Profile</button>

14. What are observables?

Observables are declarative which provide support for passing messages between publishers and subscribers in your application. They are mainly used for event handling, asynchronous programming, and handling multiple values. In this case, you define a function for publishing values, but it is not executed until a consumer subscribes to it. The subscribed consumer then receives notifications until the function completes, or until they unsubscribe.

15. What is HttpClient and its benefits?

Most of the Front-end applications communicate with backend services over HTTP protocol using either XMLHttpRequest interface or the fetch() API. Angular provides a simplified client HTTP API known as HttpClient which is based on top of XMLHttpRequest interface. This client is avaialble from @angular/common/http package. You can import in your root module as below,

import { HttpClientModule } from ‘@angular/common/http’;

The major advantages of HttpClient can be listed as below,

Contains testability features
Provides typed request and response objects
Intercept request and response
Supports Observalbe APIs
Supports streamlined error handling

By admin

Leave a Reply

Your email address will not be published. Required fields are marked *