CodeBlog.xyz

50 simple angular questions

February 11, 2024 | by codeblog.xyz

What is Angular?
Angular is a platform for building web applications. It is developed and maintained by Google. Angular is written in TypeScript and it combines declarative templates, dependency injection, end-to-end tooling, and integrated best practices to solve development challenges.

npm install -g @angular/cli
ng new my-dream-app
cd my-dream-app
ng serve

What is TypeScript and why is it used in Angular?
TypeScript is a superset of JavaScript which primarily provides optional static typing, classes, and interfaces. TypeScript brings object-oriented programming features to JavaScript. Angular is written in TypeScript because it offers superior tooling and can catch bugs at compile-time instead of at runtime.

class Student {
    fullName: string;
    constructor(public firstName: string, public middleInitial: string, public lastName: string) {
        this.fullName = firstName + " " + middleInitial + " " + lastName;
    }
}

What are Angular modules?
Angular modules, or NgModules, are a way to organize related code. Every Angular app has at least one NgModule, the root module, conventionally named AppModule. You bootstrap that module to launch the application.

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

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

What is a component in Angular?
Components are the main building block for Angular applications. Each component consists of an HTML template, CSS styles, and logic that defines the behavior of the UI.

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

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

What is dependency injection in Angular?
Dependency Injection (DI) is a design pattern that Angular uses to increase efficiency and modularity. Dependencies are services or objects that a class needs to perform its function. DI is a coding pattern in which a class asks for dependencies from external sources rather than creating them itself.

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

@Injectable({
  providedIn: 'root',
})
export class MyService {
  // service code here
}

Explain data binding in Angular.
Data binding is the automatic synchronization of data between the model (or customer object) and view components. Angular provides four types of data binding – Interpolation {{ }}, Property Binding [ ], Event Binding ( ), and Two-way Binding [( )].

<!-- Interpolation -->
<p>{{ title }}</p>

<!-- Property Binding -->
<input [value]="title">

<!-- Event Binding -->
<button (click)="sayHello()">Click me!</button>

<!-- Two-way Binding -->
<input [(ngModel)]="title">

What are Angular services?
Services are a great way to share information among classes that don’t know each other. Angular Services are a set of code that can be shared by different components of an application. Services can be used for features like database functionality, user data, and logging functionality.

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

@Injectable()
export class MyService {
  // service code here
}

What is a directive in Angular?
Directives are instructions in the DOM (Document Object Model). Angular Directives are used to customize HTML behavior in the Angular applications. There are three kinds of directives in Angular: Component Directives, Structural Directives, and Attribute Directives.

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

@Directive({
  selector: '[myDirective]',
})
export class MyDirective {
  // directive code here
}

What is routing in Angular?
Routing is a mechanism in Angular to navigate between pages in the application. When users perform certain actions or make choices, the routing system decides which view to display.

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home.component';

const routes: Routes = [
  { path: 'home', component: HomeComponent },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

What are decorators in Angular?
Decorators are a design pattern that is used to separate modification or decoration of a class without altering the source code of the original class. Angular decorators are functions that add metadata to class members (methods, properties, etc.) or classes.

@Directive({ selector: '[myDirective]' })
class MyDirective {
  constructor() { /*...*/ }
}

What is the use of @Input in Angular?
@Input is a decorator that makes a class field as an input property and supplies configuration metadata. The input property is bound to a DOM property in the template. During change detection, Angular automatically updates the data property with the DOM property’s value.

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

@Component({
  selector: 'app-child',
  template: `{{parentData}}`
})
export class ChildComponent {
  @Input() parentData: string;
}

What is the use of @Output in Angular?
@Output is a decorator that marks a class field as an output property and supplies configuration metadata. The DOM property binding updates the output property during change detection.

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

@Component({
  selector: 'app-child',
  template: `<button (click)="sendEvent()">Click me!</button>`
})
export class ChildComponent {
  @Output() event = new EventEmitter();

  sendEvent() {
    this.event.emit('Hello from child component');
  }
}

What is a Pipe in Angular?
Angular Pipes are a way to write display-value transformations that you can declare in your HTML. Examples include date and number formatting.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'exponentialStrength'})
export class ExponentialStrengthPipe implements PipeTransform {
  transform(value: number, exponent?: number): number {
    return Math.pow(value, isNaN(exponent) ? 1 : exponent);
  }
}

What is Angular CLI?
The Angular CLI is a command-line interface tool that you use to initialize, develop, scaffold, and maintain Angular applications.

npm install -g @angular/cli
ng new my-app
cd my-app
ng serve

What are Observables in Angular?
Observables are used within Angular itself, including Angular’s event system and its HTTP client service. To use Observable, Angular uses a third-party library called Reactive Extensions (RxJS).

import { Observable } from 'rxjs';

const myObservable = new Observable(observer => {
  setTimeout(() => {
    observer.next('Hello from Observable!');
  }, 2000);
});

myObservable.subscribe(value => console.log(value));

What are Promises in Angular?
Promises are a core feature of Angular and are used extensively in Angular APIs. A Promise handles a single event when an async operation completes or fails.

let myPromise = new Promise((resolve, reject) => {
  setTimeout(() => resolve('Hello from Promise!'), 2000);
});

myPromise.then(value => console.log(value));

What are the lifecycle hooks in Angular?
Lifecycle hooks are the sequence of events that happen from the birth to the death of a component or application. Some examples are ngOnInit, ngOnDestroy, ngOnChanges, etc.

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

@Component({
  selector: 'app-my-component',
  template: '<p>My Component</p>'
})
export class MyComponent implements OnInit, OnDestroy {
  ngOnInit() {
    console.log('OnInit called!');
  }

  ngOnDestroy() {
    console.log('OnDestroy called!');
  }
}

What is the use of ngFor directive in Angular?
The NgFor is a built-in structural directive, and it is used to loop over a data list and arrays to show the result on the frontend.

<ul>
  <li *ngFor="let item of items">{{ item }}</li>
</ul>

What is ngIf directive in Angular?
ngIf is a directive that is used to add an element subtree to the DOM on the basis of a {true} or {false} condition. It is used for conditional rendering of the template part from the DOM.

<div *ngIf="showDiv">Hello World!</div>

What is the purpose of ngSwitch directive in Angular?
The NgSwitch directive is used as a replacement of complex nested if-else cases for easier to read templates.

<div [ngSwitch]="value">
  <p *ngSwitchCase="'A'">Value is A</p>
  <p *ngSwitchCase="'B'">Value is B</p>
  <p *ngSwitchDefault>Value is neither A nor B</p>
</div>

What are guards in Angular?
Angular’s route guards are interfaces which can tell the router whether or not it should allow navigation to a requested route. They make this decision by looking for a true or false return value from a class which implements the given guard interface.

import { Injectable } from '@angular/core';
import { CanActivate } from '@angular/router';

@Injectable({
  providedIn: 'root',
})
export class AuthGuard implements CanActivate {
  canActivate(): boolean {
    return this.checkLogin();
  }

  checkLogin(): boolean {
    // Logic to check if user is logged in
    return true;
  }
}

What is AOT compilation in Angular?
Ahead-of-Time (AOT) is a compilation process provided by Angular to convert your Angular HTML and TypeScript code into efficient JavaScript code during the build phase before the browser downloads and runs that code.

ng build --prod

What is JIT compilation in Angular?
Just-in-Time (JIT) is a type of compilation that compiles your app in the browser at runtime. JIT compilation is the default when you run the ng build (build only) or ng serve (build and serve locally) CLI commands.

ng serve

What is the difference between AOT and JIT compilation?
JIT compiles the app in the browser at runtime, while AOT compiles the app at build time. AOT compilation results in a faster rendering in the browser, more efficient code download, and improved security compared to JIT.

# JIT compilation
ng serve

# AOT compilation
ng build --prod

What is change detection in Angular?
Change detection is a process used by Angular to track changes in the value of variables and update the DOM to reflect these changes.

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

@Component({
  selector: 'app-my-component',
  template: '<p>My Component</p>',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class MyComponent { }

What is the purpose of ElementRef in Angular?
ElementRef is a wrapper around a native element inside of a View. It is used to interact with the DOM elements.

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

@Component({
  selector: 'app-my-component',
  template: '<p>My Component</p>'
})
export class MyComponent {
  constructor(private el: ElementRef) {
    console.log(el.nativeElement);
  }
}

What is ViewEncapsulation in Angular?
Angular modifies the component’s CSS selectors so that they are only applied to the component’s view and do not affect other elements in the application.

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

@Component({
  selector: 'app-my-component',
  template: '<p>My Component</p>',
  encapsulation: ViewEncapsulation.None
})
export class MyComponent { }

What is the role of zone.js in Angular?
Zone.js is a library that provides a mechanism, called zones, for encapsulating and intercepting asynchronous operations. Angular uses zone.js to trigger change detection.

// Zone.js provides the execution context that preserves across async tasks
zone.run(() => {
  setTimeout(() => {
    console.log('Async task in zone:', Zone.current.name);
  }, 1000);
});

What are the different types of forms in Angular?
Angular provides two ways to work with forms: template-driven forms and reactive forms.

What is a template-driven form in Angular?
Template-driven forms are simple forms that are suitable for simple scenarios and fail for complex cases. They are easy to use but are not as scalable as Reactive forms.

<form #f="ngForm" (ngSubmit)="onSubmit(f)">
  <input ngModel name="name" required>
  <button type="submit">Submit</button>
</form>

What is a reactive form in Angular?
Reactive forms are more robust, scalable, reusable, and testable. They are suitable for complex scenarios.

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

form = new FormGroup({
  name: new FormControl('')
});

onSubmit() {
  console.log(this.form.value);
}

What is the difference between a template-driven form and a reactive form?
The main difference is that in template-driven forms the validation logic can be added using directives, while in reactive forms the validation logic is added in the component or service class.

What is the use of FormBuilder in Angular?
FormBuilder is a helper class that provides syntactic sugar. It reduces the amount of boilerplate code needed to build complex forms.

import { FormBuilder, Validators } from '@angular/forms';

constructor(private fb: FormBuilder) { }

form = this.fb.group({
  name: ['', Validators.required]
});

What is a structural directive in Angular?
Structural directives are responsible for HTML layout. They shape or reshape the DOM’s structure, typically by adding, removing, or manipulating elements. For example, built-in directives like *ngIf and *ngFor.

<div *ngIf="condition"></div>

What is an attribute directive in Angular?
Attribute directives change the appearance or behavior of an element, component, or another directive. For example, built-in directives like NgStyle and NgClass.

<input [ngModel]="value">

What is the use of ngModel in Angular?
ngModel is a directive which binds input, select and textarea, and stores the required user value in a variable and vice versa, if the value of the variable changes.

<input [(ngModel)]="name">

What is an EventEmitter in Angular?
EventEmitter is a class in @angular/core module that emits events when something happens and provides the ability to create custom events.

@Output() event = new EventEmitter();

onButtonClick() {
  this.event.emit('Hello World!');
}

What are Resolvers in Angular?
Resolvers are a feature in Angular Router which allows you to resolve data before a route is officially activated.

import { Injectable } from '@angular/core';
import { Resolve } from '@angular/router';
import { Observable } from 'rxjs';

@Injectable()
export class DataResolver implements Resolve<Observable<string>> {
  resolve() {
    return Observable.of('Hello World!');
  }
}

What is HTTPClient in Angular?
HTTPClient is an Angular service for reading data from web servers. It returns observable objects.

import { HttpClient } from '@angular/common/http';

constructor(private http: HttpClient) { }

getData() {
  return this.http.get('/api/data');
}

What is the role of a pipe in Angular?
Angular pipes let you declare display-value transformations in your template HTML. A class with the @Pipe decorator defines a function that transforms input values to output values for display in a view.

@Pipe({name: 'exponentialStrength'})
export class ExponentialStrengthPipe implements PipeTransform {
  transform(value: number, exponent?: number): number {
    return Math.pow(value, isNaN(exponent) ? 1 : exponent);
  }
}

What is an Async Pipe?
AsyncPipe is an impure pipe in Angular that automatically subscribes and unsubscribes to an Observable or a Promise.

<p>{{ observable | async }}</p>

What is interpolation in Angular?
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 {{ }}.

<p>{{ title }}</p>

What is Angular Universal?
Angular Universal is a technology that allows server-side rendering for Angular apps. It can generate static application pages on the server through server-side rendering (SSR).

ng add @nguniversal/express-engine
npm run build:ssr && npm run serve:ssr

What is Lazy loading in Angular?
Lazy loading is a design pattern that initializes components as needed rather than all at once. It can significantly improve performance in large Angular applications.

const routes: Routes = [
  {
    path: 'lazy',
    loadChildren: () => import('./lazy/lazy.module').then(m => m.LazyModule)
  }
];

What is ViewChild in Angular?
ViewChild is a decorator that configures a view query. The change detector looks for the first element or the directive matching the selector in the view DOM.

@ViewChild('myDiv') myDiv: ElementRef;

ngAfterViewInit() {
  console.log(this.myDiv.nativeElement.innerHTML);
}

What are Query parameters in Angular?
Query parameters in Angular allow for passing optional parameters across any route in the application. Query parameters are different from regular route parameters, which are only available on one route and are not optional.

this.router.navigate(['/path'], { queryParams: { order: 'popular' } });

What is the use of HostListener in Angular?
HostListener is a decorator that declares a DOM event to listen for and provides a handler method to run when that event occurs.

@HostListener('click', ['$event'])
onClick(event) {
  console.log('Element clicked: ', event);
}

What is a router outlet in Angular?
The RouterOutlet is a directive from the router library that is used as a component placeholder that Angular dynamically fills based on the current router state.

<router-outlet></router-outlet>

What is a service in Angular?
Services are a broad category encompassing any value, function, or feature that an application needs. A service is typically a class with a narrow, well-defined purpose. It should do something specific and do it well.

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

@Injectable()
export class MyService {
  // service code here
}

What is a resolver in Angular?
A Resolver is a class used to prevent the router from activating a route until data has been loaded. It pre-fetches data before activating a route.

import { Injectable } from '@angular/core';
import { Resolve } from '@angular/router';
import { Observable } from 'rxjs';

@Injectable()
export class DataResolver implements Resolve<Observable<string>> {
  resolve() {
    return Observable.of('Hello World!');
  }
}

What is a route guard in Angular?
Route guards are interfaces that can control navigation to and from a route. They determine if a route can be activated or deactivated, making them a great tool to implement authentication and authorization.

import { Injectable } from '@angular/core';
import { CanActivate } from '@angular/router';

@Injectable({
  providedIn: 'root',
})
export class AuthGuard implements CanActivate {
  canActivate(): boolean {
    return this.checkLogin();
  }

  checkLogin(): boolean {
    // Logic to check if user is logged in
    return true;
  }
}

RELATED POSTS

View all

view all