← IT Knowledge Base Angular · all questions

Angular — all questions in one page

The three Angular pages (Beginner, Intermediate and Advanced) merged into a single document, plus a set written for the reusable building blocks of the framework: components, modules, services, directives and pipes. 1120 questions and answers, numbered continuously, searchable, with the original wording and code samples unchanged. Search jumps straight to a question; the buttons filter by level or by topic.

1120 questions Beginner · 300 Intermediate · 380 Advanced · 426 Reusable building blocks · 14 English Angular 13+

Categories 1120 questions

Browse all questions grouped by Angular topic. Expand a branch to see the questions; click any question to jump to it.

Other / General (60)
General (60)
Components (344)
Basics (137)
Inputs & Outputs (42)
Lifecycle Hooks (50)
Host Bindings (59)
Content Projection (10)
Change Detection (46)
Services & DI (79)
Services (53)
Dependency Injection (21)
Hierarchical DI (5)
CLI, Build & Tooling (6)
Angular CLI (5)
Build & Tooling (1)
Templates & Data Binding (116)
Property & Event Binding (2)
Structural Directives (51)
Template Reference (40)
Attribute Directives (22)
Interpolation (1)
Directives (77)
Custom Directives (31)
Built-in Directives (46)
Routing & Navigation (67)
Router Basics (60)
Guards (3)
Resolvers (4)
Modules & Standalone (118)
NgModules (107)
Lazy Loading (10)
Standalone (1)
Pipes (45)
Built-in Pipes (31)
Custom Pipes (14)
Performance & Optimization (10)
Tracking / @for (5)
Profiling (2)
Virtual Scrolling (1)
Memory Leaks (1)
Bundle & Build (1)
Forms (66)
Reactive Forms (25)
Validation (21)
Dynamic Forms (13)
Template-driven (1)
FormArray (6)
HTTP & Interceptors (62)
HttpClient (60)
Interceptors (2)
Change Detection (12)
Detection Triggers (6)
Zone.js / Zoneless (6)
Architecture & State Management (13)
State Patterns (5)
NgRx (7)
Micro-frontends (1)
RxJS & Observables (16)
Observables Basics (5)
Operators (8)
Multicasting (2)
Error Handling (1)
Testing (1)
Unit Testing (1)
Security (11)
Auth & Tokens (5)
XSS & Sanitization (3)
CSP (2)
Trusted Types (1)
Signals & Reactivity (7)
Signals (6)
Resource API (1)
SSR & Hydration (7)
SSR (2)
Deferrable Views (2)
Hydration (3)
Animations, i18n & Accessibility (3)
i18n (2)
Animations (1)

Beginner 300 questions

Core concepts: components, services, dependency injection, lifecycle hooks, data binding, structural and attribute directives, pipes, routing, forms, RxJS and the CLI. Original page

Angular Framework — Basic Concepts & Core Architecture.

Guía exhaustiva de preguntas y respuestas fundamentales sobre Angular: componentes, servicios, inyección de dependencias, ciclo de vida (lifecycle hooks), enlace de datos (data binding), directivas estructurales y de atributo, pipes, enrutamiento (routing), formularios reactivos y template-driven, RxJS observables y Angular CLI.

1. What is Angular?

Angular is a TypeScript-based open-source web application framework developed by Google. It is used for building single-page applications (SPAs) with a component-based architecture.

2. What is a component in Angular?

A component is a fundamental building block of Angular applications. It consists of an HTML template, a CSS stylesheet, and a TypeScript class that defines the behavior and data of the component.


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

@Component({
    selector: 'app-example',
    template: '<h1>Hello, Angular!</h1>',
    styles: ['h1 { color: blue; }']
})
export class ExampleComponent {}
            

3. How do you define a service in Angular?

A service in Angular is a class that provides a specific functionality that can be shared across components. Services are used to handle data operations and business logic.


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

@Injectable({
    providedIn: 'root'
})
export class ExampleService {
    getData() {
        return 'Service Data';
    }
}
            

4. What is Angular CLI?

Angular CLI (Command Line Interface) is a tool used to automate the workflow of Angular applications. It helps with creating new projects, generating components, and running development servers.

5. How do you create a new Angular component using Angular CLI?

To create a new Angular component using Angular CLI, you can run the command:

ng generate component component-name

or

ng g c component-name

6. What is data binding in Angular?

Data binding is the mechanism to synchronize data between the model and the view. Angular supports several types of data binding: interpolation, property binding, event binding, and two-way data binding.


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

7. How do you use Angular directives?

Directives are classes that add behavior to elements in your Angular applications. They are used to manipulate the DOM or add new behavior to elements.


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

@Directive({
    selector: '[appHighlight]'
})
export class HighlightDirective {
    constructor(el: ElementRef, renderer: Renderer2) {
        renderer.setStyle(el.nativeElement, 'backgroundColor', 'yellow');
    }
}
            

8. What is Angular Router used for?

Angular Router is used for navigating between different views or pages in a single-page application. It allows for routing configurations and route parameters.

9. How do you define a route in Angular?

Routes are defined in the `RouterModule` configuration. Each route maps a path to a component.


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

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

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

10. What are Angular modules?

Angular modules are classes that group related components, services, directives, and pipes. They help to organize and manage the application structure.


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

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

11. What is dependency injection in Angular?

Dependency injection is a design pattern used to implement IoC (Inversion of Control). In Angular, it allows you to inject services and other dependencies into components and services.

12. How do you use `ngModel` for two-way data binding?

`ngModel` is used for two-way data binding. It binds a form input element to a property in the component.


<input [(ngModel)]="name" />
<p>Welcome, {{ name }}!</p>
            

13. What is an Angular pipe?

An Angular pipe is a way to transform data in the template. Pipes are used to format or transform data before displaying it to the user.


<p>{{ birthday | date:'longDate' }}</p>
            

14. How do you use Angular forms?

Angular supports template-driven and reactive forms. Template-driven forms use directives in the template, while reactive forms use FormControl and FormGroup classes.


import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
    selector: 'app-form',
    template: `
    <form [formGroup]="formGroup" (ngSubmit)="onSubmit()">
        <input formControlName="name" />
        <button type="submit">Submit</button>
    </form>
    `
})
export class FormComponent {
    formGroup: FormGroup;

    constructor(private fb: FormBuilder) {
        this.formGroup = this.fb.group({
            name: ['']
        });
    }

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

15. What is Angular's `ngIf` directive?

`ngIf` is a structural directive used to conditionally include or exclude elements from the DOM based on a boolean expression.


<div *ngIf="isVisible">Content to show when isVisible is true</div>
            

16. How do you pass data from a parent component to a child component in Angular?

You can pass data from a parent component to a child component using @Input properties.


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

@Component({
    selector: 'app-child',
    template: '<p>{{ data }}</p>'
})
export class ChildComponent {
    @Input() data: string;
}

@Component({
    selector: 'app-parent',
    template: '<app-child [data]="parentData"></app-child>'
})
export class ParentComponent {
    parentData = 'Hello from parent!';
}
            

17. What is Angular's `ngFor` directive used for?

`ngFor` is a structural directive used to iterate over a list or array and render a template for each item.


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

18. What is the purpose of Angular's `AppModule`?

`AppModule` is the root module of an Angular application. It is responsible for bootstrapping the application and declaring the components, directives, and services that belong to the module.

19. How do you define Angular routes?

Routes are defined using the `RouterModule` with an array of route configurations that map URL paths to components.


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

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

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

20. What are Angular lifecycle hooks?

Lifecycle hooks are methods that allow you to tap into key moments in the lifecycle of a component or directive, such as initialization and destruction.


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

@Component({
    selector: 'app-example',
    template: '<p>Example component</p>'
})
export class ExampleComponent implements OnInit, OnDestroy {
    ngOnInit() {
        console.log('Component initialized');
    }

    ngOnDestroy() {
        console.log('Component destroyed');
    }
}
            

 

Basic Angular Questions - Part 2

21. What is Angular's `ngClass` directive used for?

`ngClass` is used to dynamically add or remove CSS classes to elements based on the evaluation of expressions.


<div [ngClass]="{'active': isActive, 'inactive': !isActive}">Content</div>
            

22. How do you use Angular's `ngSwitch` directive?

`ngSwitch` is used to conditionally display one of many elements based on the value of an expression.


<div [ngSwitch]="currentColor">
    <div *ngSwitchCase="'red'">Red</div>
    <div *ngSwitchCase="'blue'">Blue</div>
    <div *ngSwitchDefault>Default</div>
</div>
            

23. What is Angular's `ngForTrackBy` used for?

`ngForTrackBy` helps Angular track which items have changed, are added, or are removed by providing a unique identifier for each item in the list.


<div *ngFor="let item of items; trackBy: trackById">
    {{ item.name }}
</div>

trackById(index: number, item: any): number {
    return item.id;
}
            

24. How do you use Angular's `ngIf` with `else`?

`ngIf` can be used with `else` to provide an alternative template when the condition is false.


<div *ngIf="isVisible; else notVisible">
    Content to show when isVisible is true
</div>
<ng-template #notVisible>
    Content to show when isVisible is false
</ng-template>
            

25. What is Angular's `FormBuilder` used for?

`FormBuilder` is a service used to create and manage reactive forms in Angular. It simplifies the creation of `FormGroup` and `FormControl` instances.


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

constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
        name: [''],
        email: ['']
    });
}
            

26. What is the purpose of Angular's `@Injectable` decorator?

The `@Injectable` decorator is used to mark a class as available for dependency injection. It tells Angular that the class can be injected into other classes as a dependency.


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

@Injectable({
    providedIn: 'root'
})
export class ExampleService {}
            

27. How do you use Angular's `@Input` and `@Output` decorators?

`@Input` is used to pass data from a parent component to a child component, while `@Output` is used to emit events from the child component to the parent.


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

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

    sendEvent() {
        this.event.emit('Event data');
    }
}
            

28. What is the Angular `AppComponent`?

`AppComponent` is typically the root component of an Angular application. It serves as the main entry point for the application and bootstraps other components.


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

@Component({
    selector: 'app-root',
    template: '<h1>Welcome to Angular!</h1>',
    styles: ['h1 { color: red; }']
})
export class AppComponent {}
            

29. How do you handle user input in Angular forms?

You can handle user input using template-driven forms or reactive forms. Template-driven forms use directives in the template, while reactive forms use form controls and groups in the component class.


import { Component } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';

@Component({
    selector: 'app-form',
    template: `
    <form [formGroup]="form" (ngSubmit)="onSubmit()">
        <input formControlName="name" />
        <button type="submit">Submit</button>
    </form>
    `
})
export class FormComponent {
    form: FormGroup;

    constructor(private fb: FormBuilder) {
        this.form = this.fb.group({
            name: ['']
        });
    }

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

30. What is Angular's `@NgModule` decorator used for?

The `@NgModule` decorator defines an Angular module, including the components, directives, and pipes it contains, as well as other modules it depends on.


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

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

31. How do you use Angular's `HttpClient` for making HTTP requests?

`HttpClient` is used to make HTTP requests to a server. It provides methods such as `get`, `post`, `put`, and `delete` for handling HTTP operations.


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

@Injectable({
    providedIn: 'root'
})
export class DataService {
    constructor(private http: HttpClient) {}

    getData() {
        return this.http.get('https://api.example.com/data');
    }
}
            

32. What is Angular's `RouterModule`?

`RouterModule` is an Angular module that provides routing and navigation functionality for Angular applications. It helps to define routes and configure navigation.


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

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

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

33. What are Angular decorators?

Decorators are functions that add metadata to classes, methods, or properties. Angular uses decorators to define components, directives, modules, and services.


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

@Component({
    selector: 'app-example',
    template: '<p>Example component</p>'
})
export class ExampleComponent {}
            

34. What is Angular's `@ViewChild` decorator used for?

The `@ViewChild` decorator is used to access a child component, directive, or DOM element from the parent component's class.


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

@Component({
    selector: 'app-example',
    template: '<input #inputElement />'
})
export class ExampleComponent {
    @ViewChild('inputElement') input: ElementRef;

    ngAfterViewInit() {
        this.input.nativeElement.focus();
    }
}
            

35. How do you create a custom Angular directive?

A custom directive is created using the `@Directive` decorator. It can be used to add behavior to elements or components.


import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';

@Directive({
    selector: '[appHighlight]'
})
export class HighlightDirective {
    constructor(private el: ElementRef, private renderer: Renderer2) {}

    @HostListener('mouseenter') onMouseEnter() {
        this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow');
    }

    @HostListener('mouseleave') onMouseLeave() {
        this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'white');
    }
}
            

36. What is Angular's `ChangeDetectionStrategy`?

`ChangeDetectionStrategy` determines how Angular checks for changes in the component. The two strategies are `Default` and `OnPush`.


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

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

37. How do you use Angular's `ngModel` for two-way data binding?

`ngModel` is used for two-way data binding between the model and the view. It binds a form control to a property in the component class.


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

@Component({
    selector: 'app-example',
    template: '<input [(ngModel)]="name" /> <p>Hello {{ name }}</p>'
})
export class ExampleComponent {
    name: string = '';
}
            

38. What is Angular's `@HostBinding` decorator used for?

The `@HostBinding` decorator binds a property or attribute of the host element of a directive or component to a property of the directive or component.


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

@Directive({
    selector: '[appHighlight]'
})
export class HighlightDirective {
    @HostBinding('class.highlight') isHighlighted = true;
}
            

39. What is Angular's `ng-content` used for?

`ng-content` is used to project content into a component from its parent component. It allows you to create reusable components with customizable content.


@Component({
    selector: 'app-card',
    template: '<ng-content></ng-content>'
})
export class CardComponent {}
            

40. How do you use Angular's `Router` service to navigate programmatically?

You can use the `Router` service to navigate to different routes programmatically by calling its `navigate` method.


import { Router } from '@angular/router';

constructor(private router: Router) {}

navigateToHome() {
    this.router.navigate(['/home']);
}
            

Basic Angular Questions - Part 3

41. What is the purpose of Angular's `ngOnInit` lifecycle hook?

The `ngOnInit` lifecycle hook is called after the component's data-bound properties have been initialized. It is commonly used for initialization logic.


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

@Component({
    selector: 'app-example',
    template: '<p>Example component</p>'
})
export class ExampleComponent implements OnInit {
    ngOnInit() {
        console.log('Component initialized');
    }
}
            

42. How do you define an Angular service?

An Angular service is defined using the `@Injectable` decorator. It is a class that can be injected into other components or services.


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

@Injectable({
    providedIn: 'root'
})
export class DataService {
    getData() {
        return ['data1', 'data2'];
    }
}
            

43. What is the purpose of Angular's `@Directive` decorator?

The `@Directive` decorator is used to create custom directives in Angular. Directives can change the appearance or behavior of elements in the DOM.


import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';

@Directive({
    selector: '[appHighlight]'
})
export class HighlightDirective {
    constructor(private el: ElementRef, private renderer: Renderer2) {}

    @HostListener('mouseenter') onMouseEnter() {
        this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow');
    }

    @HostListener('mouseleave') onMouseLeave() {
        this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'transparent');
    }
}
            

44. How do you create an Angular module?

An Angular module is created using the `@NgModule` decorator. It defines a module that groups components, directives, pipes, and services.


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

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

45. What is Angular's `ngIf` directive?

`ngIf` is a structural directive that conditionally includes or removes an element from the DOM based on the truthiness of an expression.


<div *ngIf="isVisible">This is visible</div>
            

46. How do you use Angular's `ngFor` directive?

`ngFor` is a structural directive used to repeat a block of HTML for each item in a list.


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

47. What is Angular's `@Component` decorator?

The `@Component` decorator is used to define a component in Angular. It specifies the selector, template, and styles for the component.


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

@Component({
    selector: 'app-example',
    template: '<p>Example component</p>',
    styles: ['p { color: blue; }']
})
export class ExampleComponent {}
            

48. How do you implement Angular's dependency injection?

Dependency injection in Angular is implemented by providing services in the component's or module's `providers` array and injecting them into the constructor of the class.


import { Component } from '@angular/core';
import { DataService } from './data.service';

@Component({
    selector: 'app-example',
    template: '<p>Example component</p>'
})
export class ExampleComponent {
    constructor(private dataService: DataService) {}
}
            

49. What is Angular's `@Pipe` decorator used for?

The `@Pipe` decorator is used to define custom pipes in Angular, which transform data in templates.


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

@Pipe({
    name: 'customPipe'
})
export class CustomPipe implements PipeTransform {
    transform(value: string): string {
        return value.toUpperCase();
    }
}
            

50. How do you use Angular's `ngOnChanges` lifecycle hook?

The `ngOnChanges` lifecycle hook is called when an input property of the component changes. It is used to perform actions based on the input property changes.


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

@Component({
    selector: 'app-example',
    template: '<p>Example component</p>'
})
export class ExampleComponent implements OnChanges {
    @Input() data: string;

    ngOnChanges(changes: SimpleChanges) {
        console.log('Changes detected:', changes);
    }
}
            

51. What is Angular's `ngModel` directive?

`ngModel` is a directive used for two-way data binding between the form controls and component properties.

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

52. How do you create a reactive form in Angular?

Reactive forms are created using `FormGroup` and `FormControl` classes from `@angular/forms`.


import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
    selector: 'app-form',
    template: `
    <form [formGroup]="form" (ngSubmit)="onSubmit()">
        <input formControlName="name" />
        <button type="submit">Submit</button>
    </form>
    `
})
export class FormComponent {
    form: FormGroup;

    constructor(private fb: FormBuilder) {
        this.form = this.fb.group({
            name: ['']
        });
    }

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

53. What is Angular's `@HostListener` decorator used for?

The `@HostListener` decorator is used to listen to events on the host element of the directive or component.


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

@Directive({
    selector: '[appEvent]'
})
export class EventDirective {
    @HostListener('click', ['$event']) onClick(event: Event) {
        console.log('Element clicked:', event);
    }
}
            

54. How do you use Angular's `@Input` decorator?

The `@Input` decorator is used to pass data from a parent component to a child component.


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

@Component({
    selector: 'app-child',
    template: '<p>{{ data }}</p>'
})
export class ChildComponent {
    @Input() data: string;
}
            

55. What is Angular's `@Output` decorator used for?

The `@Output` decorator is used to emit events from a child component to a parent component.


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

@Component({
    selector: 'app-child',
    template: '<button (click)="sendData()">Send Data</button>'
})
export class ChildComponent {
    @Output() dataSent = new EventEmitter<string>();

    sendData() {
        this.dataSent.emit('Some data');
    }
}
            

56. How do you handle HTTP requests in Angular?

HTTP requests in Angular are handled using the `HttpClient` service from `@angular/common/http`.


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

@Component({
    selector: 'app-http',
    template: '<p>HTTP request component</p>'
})
export class HttpComponent {
    constructor(private http: HttpClient) {}

    getData() {
        this.http.get('https://api.example.com/data').subscribe(response => {
            console.log(response);
        });
    }
}
            

57. What is Angular's `RouterModule` used for?

The `RouterModule` is used to configure routes in an Angular application, allowing navigation between different views or components.


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

const routes: Routes = [
    { path: 'home', component: HomeComponent },
    { path: 'about', component: AboutComponent },
    { path: '', redirectTo: '/home', pathMatch: 'full' }
];

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

58. How do you use Angular's `@Injectable` decorator in a service?

The `@Injectable` decorator is used to define a service that can be injected into other components or services.


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

@Injectable({
    providedIn: 'root'
})
export class UserService {
    getUser() {
        return { name: 'John Doe' };
    }
}
            

59. What is Angular's `@NgModule` metadata `imports` property used for?

The `imports` property in `@NgModule` is used to import other Angular modules into the current module, making their components, directives, and pipes available for use.


import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';

@NgModule({
    imports: [CommonModule, FormsModule],
    declarations: [MyComponent]
})
export class MyModule {}
            

60. How do you use Angular's `@HostBinding` decorator?

The `@HostBinding` decorator is used to bind a property or attribute of the host element to a property of the directive or component.


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

@Directive({
    selector: '[appColor]'
})
export class ColorDirective {
    @HostBinding('style.color') color: string = 'blue';
}
            

Basic Angular Questions - Part 4

61. What is Angular's `@ViewChild` decorator used for?

The `@ViewChild` decorator is used to access a child component, directive, or DOM element within the component's template.


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

@Component({
    selector: 'app-example',
    template: '<input #myInput />'
})
export class ExampleComponent implements AfterViewInit {
    @ViewChild('myInput') input: ElementRef;

    ngAfterViewInit() {
        this.input.nativeElement.focus();
    }
}
            

62. How do you define Angular routes with parameters?

Angular routes with parameters are defined using a colon `:` followed by the parameter name in the route path.


const routes: Routes = [
    { path: 'user/:id', component: UserComponent }
];
            

63. What is Angular's `ngSwitch` directive used for?

The `ngSwitch` directive is used to conditionally include or exclude elements from the DOM based on a switch expression.


<div [ngSwitch]="value">
    <p *ngSwitchCase="'case1'">Case 1</p>
    <p *ngSwitchCase="'case2'">Case 2</p>
    <p *ngSwitchDefault>Default case</p>
</div>
            

64. How do you use Angular's `ngStyle` directive?

The `ngStyle` directive is used to apply inline styles to elements based on the values of an expression.


<div [ngStyle]="{'color': color, 'font-size.px': fontSize}">
    Styled text
</div>
            

65. What is Angular's `ngContainer` element?

The `ngContainer` is a structural directive that allows you to group elements without adding extra elements to the DOM.

<ng-container *ngIf="isVisible">
    </ng-container><ng-container *ngIf="isVisible"><p>Content is visible</p>
</ng-container>
            

66. How do you define Angular's route guards?

Route guards are used to control access to routes. They implement the `CanActivate`, `CanDeactivate`, `CanLoad`, or `Resolve` interfaces.


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

@Injectable({
    providedIn: 'root'
})
export class AuthGuard implements CanActivate {
    constructor(private router: Router) {}

    canActivate(): boolean {
        // Implement authentication check
        return true; // or false if not authenticated
    }
}
            

67. What is Angular's `@HostBinding` decorator used for?

The `@HostBinding` decorator is used to bind a property or attribute of the host element to a property of the directive or component.


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

@Directive({
    selector: '[appHighlight]'
})
export class HighlightDirective {
    @HostBinding('class.highlight') isHighlighted = true;
}
            

68. How do you perform form validation in Angular's reactive forms?

Form validation in reactive forms is done using validators such as `Validators.required`, `Validators.minLength`, etc.


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

@Component({
    selector: 'app-form',
    template: `
    <form [formGroup]="form" (ngSubmit)="onSubmit()">
        <input formControlName="name" />
        <div *ngIf="form.get('name').invalid && form.get('name').touched">
            Name is required
        </div>
        <button type="submit">Submit</button>
    </form>
    `
})
export class FormComponent {
    form: FormGroup;

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

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

69. What is Angular's `@NgModule` metadata `declarations` property used for?

The `declarations` property in `@NgModule` is used to declare the components, directives, and pipes that belong to the module.


import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MyComponent } from './my.component';

@NgModule({
    declarations: [MyComponent],
    imports: [CommonModule],
    exports: [MyComponent]
})
export class MyModule {}
            

70. How do you use Angular's `ngModel` directive for two-way data binding?

The `ngModel` directive is used for two-way data binding by binding form controls to component properties.

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

71. What is Angular's `@Injectable` decorator used for in services?

The `@Injectable` decorator is used to mark a class as available to be provided and injected as a dependency in other components or services.


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

@Injectable({
    providedIn: 'root'
})
export class MyService {
    getData() {
        return 'Service data';
    }
}
            

72. How do you handle HTTP errors in Angular using `HttpClient`?

HTTP errors can be handled using the `catchError` operator from `rxjs` to catch and handle errors from HTTP requests.


import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs';

@Injectable({
    providedIn: 'root'
})
export class DataService {
    constructor(private http: HttpClient) {}

    getData() {
        return this.http.get('https://api.example.com/data').pipe(
            catchError(error => {
                console.error('Error occurred', error);
                return of([]);
            })
        );
    }
}
            

73. What is Angular's `@NgModule` metadata `providers` property used for?

The `providers` property in `@NgModule` is used to define the services that will be available for dependency injection within the module.


import { NgModule } from '@angular/core';
import { MyService } from './my.service';

@NgModule({
    providers: [MyService]
})
export class MyModule {}
            

74. How do you use Angular's `*ngFor` directive?

The `*ngFor` directive is used to iterate over a list and create a template for each item in the list.


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

75. How do you use Angular's `ngIf` directive?

The `ngIf` directive is used to conditionally include or exclude elements from the DOM based on an expression.


<div *ngIf="isVisible">
    Content is visible
</div>
            

76. What is Angular's `@Input` decorator used for?

The `@Input` decorator is used to pass data from a parent component to a child component.


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

@Component({
    selector: 'app-child',
    template: '<p>{{ data }}</p>'
})
export class ChildComponent {
    @Input() data: string;
}
            

77. What is the role of the `AppComponent` in an Angular application?

The `AppComponent` is the root component of the Angular application and serves as the entry point for the component tree.


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

@Component({
    selector: 'app-root',
    template: '<h1>Welcome to Angular!</h1>'
})
export class AppComponent {}
            

78. How do you create a custom Angular directive?

Custom directives are created by using the `@Directive` decorator to define a class that will be applied to elements.


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

@Directive({
    selector: '[appHighlight]'
})
export class HighlightDirective {
    constructor(private el: ElementRef, private renderer: Renderer2) {
        this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow');
    }
}
            

79. What is Angular's `ngOnInit` lifecycle hook used for?

The `ngOnInit` lifecycle hook is used for initialization logic that needs to be performed after the component's data-bound properties have been initialized.


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

@Component({
    selector: 'app-example',
    template: '<p>Example component</p>'
})
export class ExampleComponent implements OnInit {
    ngOnInit() {
        console.log('Component initialized');
    }
}
            

80. How do you handle user input with Angular forms?

User input is handled using Angular forms, which can be either template-driven or reactive forms.


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

@Component({
    selector: 'app-login',
    template: `
    <form [formGroup]="loginForm" (ngSubmit)="onSubmit()">
        <input formControlName="username" />
        <input formControlName="password" type="password" />
        <button type="submit">Login</button>
    </form>
    `
})
export class LoginComponent {
    loginForm: FormGroup;

    constructor(private fb: FormBuilder) {
        this.loginForm = this.fb.group({
            username: ['', Validators.required],
            password: ['', Validators.required]
        });
    }

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

Basic Angular Questions - Part 5

81. What is Angular's `ngModel` directive used for?

The `ngModel` directive is used for two-way data binding between the form input fields and the component properties.

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

82. How do you define a custom Angular pipe?

A custom pipe is defined by using the `@Pipe` decorator and implementing the `PipeTransform` interface.


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

@Pipe({
    name: 'reverse'
})
export class ReversePipe implements PipeTransform {
    transform(value: string): string {
        return value.split('').reverse().join('');
    }
}
            

83. What is Angular's `ngFor` directive used for?

The `ngFor` directive is used to repeat a template for each item in a list or array.


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

84. How do you use Angular's `ngClass` directive?

The `ngClass` directive is used to dynamically add or remove CSS classes based on the expression.


<div [ngClass]="{ 'highlight': isHighlighted, 'bold': isBold }">
    Styled text
</div>
            

85. What is the purpose of Angular's `@Output` decorator?

The `@Output` decorator is used to define an event that a child component can emit to its parent component.


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

@Component({
    selector: 'app-child',
    template: `<button (click)="sendMessage()">Send</button>`
})
export class ChildComponent {
    @Output() message = new EventEmitter<string>();

    sendMessage() {
        this.message.emit('Hello from child');
    }
}
            

86. How do you bind an Angular component property to an HTML element attribute?

You can bind a component property to an HTML element attribute using property binding syntax with square brackets.


<img [src]="imageUrl" />
            

87. What is the purpose of Angular's `ngIf` directive?

The `ngIf` directive is used to conditionally include or exclude elements from the DOM based on a boolean expression.


<div *ngIf="isVisible">Content is visible</div>
            

88. How do you use Angular's `@ViewChild` decorator to access a child component?

The `@ViewChild` decorator is used to access a child component or element within the component's template.


import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { ChildComponent } from './child.component';

@Component({
    selector: 'app-parent',
    template: `<app-child></app-child>`
})
export class ParentComponent implements AfterViewInit {
    @ViewChild(ChildComponent) child: ChildComponent;

    ngAfterViewInit() {
        console.log(this.child);
    }
}
            

89. What is Angular's `@Injectable` decorator used for?

The `@Injectable` decorator is used to mark a class as available for dependency injection.


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

@Injectable({
    providedIn: 'root'
})
export class MyService {
    getValue() {
        return 'Service value';
    }
}
            

90. How do you create a reactive form in Angular?

Reactive forms are created using the `FormBuilder` service to construct the form model and its controls.


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

@Component({
    selector: 'app-reactive-form',
    template: `
    <form [formGroup]="form" (ngSubmit)="onSubmit()">
        <input formControlName="name" />
        <button type="submit">Submit</button>
    </form>
    `
})
export class ReactiveFormComponent {
    form: FormGroup;

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

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

91. What is the role of the `app.module.ts` file in an Angular application?

The `app.module.ts` file defines the root module of the application, including the components, directives, pipes, and services that are used throughout the app.


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

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

92. How do you handle events in Angular?

Events are handled using Angular's event binding syntax, with parentheses around the event name.


<button (click)="handleClick()">Click me</button>
            

93. How do you use Angular's `ngSwitch` directive?

The `ngSwitch` directive is used to conditionally display elements based on the value of an expression.


<div [ngSwitch]="value">
    <p *ngSwitchCase="'case1'">Case 1</p>
    <p *ngSwitchCase="'case2'">Case 2</p>
    <p *ngSwitchDefault>Default case</p>
</div>
            

94. How do you define Angular routes with child routes?

Child routes are defined within the `children` property of a route configuration object.


const routes: Routes = [
    { path: 'parent', component: ParentComponent, children: [
        { path: 'child', component: ChildComponent }
    ]}
];
            

95. What is Angular's `ngOnChanges` lifecycle hook used for?

The `ngOnChanges` lifecycle hook is used to respond to changes in input properties of the component.


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

@Component({
    selector: 'app-example',
    template: '<p>{{ value }}</p>'
})
export class ExampleComponent implements OnChanges {
    @Input() value: string;

    ngOnChanges(changes: SimpleChanges) {
        console.log('Changes:', changes);
    }
}
            

96. How do you create a service in Angular and provide it in the root injector?

A service can be created using the `@Injectable` decorator with the `providedIn: 'root'` option to make it available throughout the application.


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

@Injectable({
    providedIn: 'root'
})
export class ExampleService {
    getData() {
        return 'Some data';
    }
}
            

97. How do you use Angular's `ngStyle` directive to apply styles dynamically?

The `ngStyle` directive is used to apply styles dynamically based on an expression.


<div [ngStyle]="{ 'color': color, 'font-size': fontSize }">
    Styled text
</div>
            

98. What is Angular's `@HostListener` decorator used for?

The `@HostListener` decorator is used to listen to events on the host element of the directive or component.


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

@Directive({
    selector: '[appHover]'
})
export class HoverDirective {
    @HostListener('mouseenter') onMouseEnter() {
        console.log('Mouse entered');
    }

    @HostListener('mouseleave') onMouseLeave() {
        console.log('Mouse left');
    }
}
            

99. How do you handle HTTP requests in Angular?

HTTP requests are handled using the `HttpClient` service provided by the `@angular/common/http` module.


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

@Component({
    selector: 'app-http',
    template: '<p>Check console for HTTP request result</p>'
})
export class HttpComponent {
    constructor(private http: HttpClient) {
        this.http.get('https://api.example.com/data')
            .subscribe(data => console.log(data));
    }
}
            

100. How do you use Angular's `ngOnDestroy` lifecycle hook?

The `ngOnDestroy` lifecycle hook is used to clean up resources and unsubscribe from observables when a component is destroyed.


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

@Component({
    selector: 'app-example',
    template: '<p>Example component</p>'
})
export class ExampleComponent implements OnDestroy {
    private subscription: Subscription;

    constructor() {
        this.subscription = // ... initialize subscription
    }

    ngOnDestroy() {
        this.subscription.unsubscribe();
    }
}
            

Basic Angular Questions - Part 6

101. What is Angular's `ngModel` directive used for?

The `ngModel` directive is used for two-way data binding between form input fields and component properties.

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

102. How do you define a custom Angular pipe?

A custom pipe is defined by using the `@Pipe` decorator and implementing the `PipeTransform` interface.


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

@Pipe({
    name: 'reverse'
})
export class ReversePipe implements PipeTransform {
    transform(value: string): string {
        return value.split('').reverse().join('');
    }
}
            

103. What is Angular's `ngFor` directive used for?

The `ngFor` directive is used to repeat a template for each item in a list or array.


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

104. How do you use Angular's `ngClass` directive?

The `ngClass` directive is used to dynamically add or remove CSS classes based on the expression.


<div [ngClass]="{ 'highlight': isHighlighted, 'bold': isBold }">
    Styled text
</div>
            

105. What is the purpose of Angular's `@Output` decorator?

The `@Output` decorator is used to define an event that a child component can emit to its parent component.


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

@Component({
    selector: 'app-child',
    template: `<button (click)="sendMessage()">Send</button>`
})
export class ChildComponent {
    @Output() message = new EventEmitter<string>();

    sendMessage() {
        this.message.emit('Hello from child');
    }
}
            

106. How do you bind an Angular component property to an HTML element attribute?

You can bind a component property to an HTML element attribute using property binding syntax with square brackets.


<img alt="" [src]="imageUrl" />
            

107. What is the purpose of Angular's `ngIf` directive?

The `ngIf` directive is used to conditionally include or exclude elements from the DOM based on a boolean expression.


<div *ngIf="isVisible">Content is visible</div>
            

108. How do you use Angular's `@ViewChild` decorator to access a child component?

The `@ViewChild` decorator is used to access a child component or element within the component's template.


import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { ChildComponent } from './child.component';

@Component({
    selector: 'app-parent',
    template: `<app-child></app-child>`
})
export class ParentComponent implements AfterViewInit {
    @ViewChild(ChildComponent) child: ChildComponent;

    ngAfterViewInit() {
        console.log(this.child);
    }
}
            

109. What is Angular's `@Injectable` decorator used for?

The `@Injectable` decorator is used to mark a class as available for dependency injection.


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

@Injectable({
    providedIn: 'root'
})
export class MyService {
    getValue() {
        return 'Service value';
    }
}
            

110. How do you create a reactive form in Angular?

Reactive forms are created using the `FormBuilder` service to construct the form model and its controls.


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

@Component({
    selector: 'app-reactive-form',
    template: `
    <form [formGroup]="form" (ngSubmit)="onSubmit()">
        <input formControlName="name" />
        <button type="submit">Submit</button>
    </form>
    `
})
export class ReactiveFormComponent {
    form: FormGroup;

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

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

111. What is the role of the `app.module.ts` file in an Angular application?

The `app.module.ts` file defines the root module of the application, including the components, directives, pipes, and services that are used throughout the app.


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

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

112. How do you handle events in Angular?

Events are handled using Angular's event binding syntax, with parentheses around the event name.


<button (click)="handleClick()">Click me</button>
            

113. How do you use Angular's `ngSwitch` directive?

The `ngSwitch` directive is used to conditionally display elements based on the value of an expression.


<div [ngSwitch]="value">
    <p *ngSwitchCase="'case1'">Case 1</p>
    <p *ngSwitchCase="'case2'">Case 2</p>
    <p *ngSwitchDefault>Default case</p>
</div>
            

114. How do you define Angular routes with child routes?

Child routes are defined within the `children` property of a route configuration object.


const routes: Routes = [
    { path: 'parent', component: ParentComponent, children: [
        { path: 'child', component: ChildComponent }
    ]}
];
            

115. What is Angular's `@OnChanges` lifecycle hook used for?

The `ngOnChanges` lifecycle hook is used to respond to changes in input properties of the component.


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

@Component({
    selector: 'app-example',
    template: '<p>{{ value }}</p>'
})
export class ExampleComponent implements OnChanges {
    @Input() value: string;

    ngOnChanges(changes: SimpleChanges) {
        console.log('Changes:', changes);
    }
}
            

116. How do you create a service in Angular and provide it in the root injector?

A service can be created using the `@Injectable` decorator with the `providedIn: 'root'` option to make it available throughout the application.


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

@Injectable({
    providedIn: 'root'
})
export class ExampleService {
    getData() {
        return 'Some data';
    }
}
            

117. How do you use Angular's `ngStyle` directive to apply styles dynamically?

The `ngStyle` directive is used to apply styles dynamically based on an expression.


<div [ngStyle]="{ 'color': color, 'font-size': fontSize }">
    Styled text
</div>
            

118. What is Angular's `@HostListener` decorator used for?

The `@HostListener` decorator is used to listen to events on the host element of the directive or component.


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

@Directive({
    selector: '[appHover]'
})
export class HoverDirective {
    @HostListener('mouseenter') onMouseEnter() {
        console.log('Mouse entered');
    }

    @HostListener('mouseleave') onMouseLeave() {
        console.log('Mouse left');
    }
}
            

119. How do you handle HTTP requests in Angular?

HTTP requests are handled using the `HttpClient` service provided by the `@angular/common/http` module.


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

@Component({
    selector: 'app-http',
    template: '<p>Check console for HTTP request result</p>'
})
export class HttpComponent {
    constructor(private http: HttpClient) {
        this.http.get('https://api.example.com/data')
            .subscribe(data => console.log(data));
    }
}
            

120. How do you use Angular's `ngOnDestroy` lifecycle hook?

The `ngOnDestroy` lifecycle hook is used to clean up resources and unsubscribe from observables when a component is destroyed.


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

@Component({
    selector: 'app-example',
    template: '<p>Example component</p>'
})
export class ExampleComponent implements OnDestroy {
    private subscription: Subscription;

    constructor() {
        this.subscription = // ... initialize subscription
    }

    ngOnDestroy() {
        this.subscription.unsubscribe();
    }
}
            

Basic Angular Questions - Part 8

121. What is the purpose of the `ngOnInit` lifecycle hook?

The `ngOnInit` lifecycle hook is used for component initialization, including fetching data and setting up component properties.


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

@Component({
    selector: 'app-example',
    template: '<p>{{ message }}</p>'
})
export class ExampleComponent implements OnInit {
    message: string;

    ngOnInit() {
        this.message = 'Component initialized';
    }
}
            

122. How do you use Angular's `ngModel` with forms?

The `ngModel` directive binds form control values to component properties, supporting two-way data binding in forms.


<form>
    <input [(ngModel)]="username" name="username" />
    <p>Your username is: {{ username }}</p>
</form>
            

123. How do you define and use a service in Angular?

A service is defined with the `@Injectable` decorator and can be injected into components or other services.


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

@Injectable({
    providedIn: 'root'
})
export class DataService {
    getData() {
        return ['Item 1', 'Item 2'];
    }
}
            

124. How do you configure Angular routing?

Routing is configured using the `RouterModule.forRoot` method, providing route definitions in the application module.


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

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

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

125. How do you implement input validation in Angular forms?

Validation is implemented using Angular’s built-in validators or custom validators on form controls.


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

@Component({
    selector: 'app-validation-form',
    template: `
    <form [formGroup]="form" (ngSubmit)="onSubmit()">
        <input formControlName="email" placeholder="Email" />
        <div *ngIf="form.get('email').invalid && form.get('email').touched">
            <p>Email is required and must be valid</p>
        </div>
        <button type="submit">Submit</button>
    </form>
    `
})
export class ValidationFormComponent {
    form: FormGroup;

    constructor(private fb: FormBuilder) {
        this.form = this.fb.group({
            email: ['', [Validators.required, Validators.email]]
        });
    }


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

126. How do you use Angular's `ngFor` directive with objects?

When using `ngFor` with objects, you can iterate over the object's keys using the `keyvalue` pipe.


<ul>
    <li *ngFor="let item of object | keyvalue">{{ item.key }}: {{ item.value }}</li>
</ul>
            

127. What is the purpose of the `ngAfterViewInit` lifecycle hook?

The `ngAfterViewInit` lifecycle hook is used to perform actions after Angular initializes the component's view and child views.


import { Component, AfterViewInit, ViewChild } from '@angular/core';
import { ChildComponent } from './child.component';

@Component({
    selector: 'app-parent',
    template: `<app-child></app-child>`
})
export class ParentComponent implements AfterViewInit {
    @ViewChild(ChildComponent) child: ChildComponent;

    ngAfterViewInit() {
        console.log('Child component:', this.child);
    }
}
            

128. How do you dynamically set CSS styles in Angular?

You can dynamically set CSS styles using Angular’s `[ngStyle]` directive.


<div [ngStyle]="{ 'color': color, 'font-size': fontSize }">
    Dynamic style content
</div>
            

129. How do you create a module in Angular?

A module is created using the `@NgModule` decorator and can include declarations, imports, providers, and bootstrap components.


import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FeatureComponent } from './feature.component';

@NgModule({
    declarations: [FeatureComponent],
    imports: [CommonModule],
    exports: [FeatureComponent]
})
export class FeatureModule {}
            

130. How do you use Angular's `ngSwitch` directive?

The `ngSwitch` directive allows you to display elements based on a matched value.


<div [ngSwitch]="value">
    <div *ngSwitchCase="'case1'">Case 1</div>
    <div *ngSwitchCase="'case2'">Case 2</div>
    <div *ngSwitchDefault>Default case</div>
</div>
            

131. How do you handle HTTP requests in Angular?

HTTP requests are handled using Angular’s `HttpClient` service.


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

@Component({
    selector: 'app-http',
    template: '<p>Data: {{ data }}</p>'
})
export class HttpComponent {
    data: any;

    constructor(private http: HttpClient) {
        this.http.get('https://api.example.com/data')
            .subscribe(response => this.data = response);
    }
}
            

132. What is the purpose of the `@Input` decorator?

The `@Input` decorator is used to define properties that can receive data from a parent component.


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

@Component({
    selector: 'app-child',
    template: '<p>{{ data }}</p>'
})
export class ChildComponent {
    @Input() data: string;
}
            

133. How do you use Angular's `ngClass` directive?

The `ngClass` directive dynamically sets CSS classes on an element based on conditions.


<div [ngClass]="{ 'active': isActive, 'inactive': !isActive }">
    Conditional classes
</div>
            

134. How do you create a component with Angular CLI?

You can create a component using the Angular CLI command `ng generate component` or `ng g c`.


ng generate component my-component
            

135. What is Angular's `ng-content` used for?

The `ng-content` directive is used for content projection, allowing you to insert content into a component’s template.


@Component({
    selector: 'app-wrapper',
    template: '<ng-content></ng-content>'
})
export class WrapperComponent {}
            

136. How do you use Angular's `@ViewChild` decorator?

The `@ViewChild` decorator is used to query a single child element or component.


import { Component, ViewChild } from '@angular/core';
import { ChildComponent } from './child.component';

@Component({
    selector: 'app-parent',
    template: `<app-child></app-child>`
})
export class ParentComponent {
    @ViewChild(ChildComponent) child: ChildComponent;
}
            

137. What is the purpose of the `@Output` decorator?

The `@Output` decorator is used to define an event that a child component can emit to its parent component.


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

@Component({
    selector: 'app-child',
    template: '<button (click)="sendMessage()">Send</button>'
})
export class ChildComponent {
    @Output() messageEvent = new EventEmitter<string>();

    sendMessage() {
        this.messageEvent.emit('Hello from child');
    }
}
            

138. How do you handle errors in Angular HTTP requests?

Errors in HTTP requests can be handled using the `catchError` operator in RxJS.


import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs';

@Component({
    selector: 'app-http',
    template: '<p>Data: {{ data }}</p>'
})
export class HttpComponent {
    data: any;

    constructor(private http: HttpClient) {
        this.http.get('https://api.example.com/data')
            .pipe(
                catchError(error => {
                    console.error('Error:', error);
                    return of([]);
                })
            )
            .subscribe(response => this.data = response);
    }
}
            

139. How do you create a route with parameters in Angular?

Routes with parameters are defined using a colon `:` followed by the parameter name.


const routes: Routes = [
    { path: 'user/:id', component: UserComponent }
];
            

140. What is Angular's `ngOnDestroy` lifecycle hook used for?

The `ngOnDestroy` lifecycle hook is used to perform cleanup tasks when the component is destroyed.


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

@Component({
    selector: 'app-example',
    template: '<p>Component with cleanup</p>'
})
export class ExampleComponent implements OnDestroy {
    ngOnDestroy() {
        console.log('Component destroyed');
    }
}
            

 

Basic Angular Questions - Part 15

141. How do you use Angular's `@Output` decorator to create custom events?

The `@Output` decorator is used to create custom events that a component can emit.


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

@Component({
    selector: 'app-custom-button',
    template: '<button (click)="onClick()">Click me</button>'
})
export class CustomButtonComponent {
    @Output() clicked = new EventEmitter<void>();

    onClick() {
        this.clicked.emit();
    }
}
            

142. What is Angular's `@ViewChild` decorator and how is it used?

The `@ViewChild` decorator is used to get a reference to a child component or element in the template.


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

@Component({
    selector: 'app-example',
    template: '<input #inputElement />'
})
export class ExampleComponent {
    @ViewChild('inputElement') input!: ElementRef;

    ngAfterViewInit() {
        this.input.nativeElement.focus();
    }
}
            

143. How do you use Angular's `ngIf` directive to conditionally display elements?

The `ngIf` directive is used to include or exclude elements based on a condition.


<div *ngIf="isVisible">This content is visible</div>
            

144. What is Angular's `@Injectable` decorator used for?

The `@Injectable` decorator is used to define a service that can be injected into components or other services.


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

@Injectable({
    providedIn: 'root'
})
export class ExampleService {
    getData() {
        return 'Data';
    }
}
            

145. How do you use Angular's `ngFor` directive to iterate over an object?

The `ngFor` directive can be used to iterate over objects by using the key-value pair syntax.


<div *ngFor="let key of objectKeys(myObject)">
    {{ key }}: {{ myObject[key] }}
</div>

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent {
    myObject = { a: 1, b: 2, c: 3 };
    objectKeys = Object.keys;
}
            

146. What is Angular's `@HostBinding` decorator used for?

The `@HostBinding` decorator is used to bind a property of the host element to a property in the directive or component.


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

@Directive({
    selector: '[appHighlight]'
})
export class HighlightDirective {
    @HostBinding('class.highlighted') isHighlighted = true;
}
            

147. How do you create a pipe that filters a list of items in Angular?

A custom pipe can be created to filter a list based on a condition.


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

@Pipe({ name: 'filterList' })
export class FilterListPipe implements PipeTransform {
    transform(items: any[], searchText: string): any[] {
        if (!items) return [];
        if (!searchText) return items;
        searchText = searchText.toLowerCase();
        return items.filter(item => item.toLowerCase().includes(searchText));
    }
}
            

148. What is Angular's `@ContentChild` decorator used for?

The `@ContentChild` decorator is used to get a reference to a child element projected into the component's view.


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

@Component({
    selector: 'app-parent',
    template: '<ng-content></ng-content>'
})
export class ParentComponent implements AfterContentInit {
    @ContentChild('content') content!: ElementRef;

    ngAfterContentInit() {
        console.log(this.content.nativeElement.textContent);
    }
}
            

149. How do you use Angular's `@Input` decorator to pass data to a component?

The `@Input` decorator is used to pass data from a parent component to a child component.


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

@Component({
    selector: 'app-child',
    template: '<p>{{ data }}</p>'
})
export class ChildComponent {
    @Input() data!: string;
}
            

150. How do you use Angular's `ngClass` directive to apply classes conditionally?

The `ngClass` directive can be used to conditionally apply CSS classes based on a condition.


<div [ngClass]="{ 'active': isActive, 'inactive': !isActive }">
    Content
</div>
            

151. What is Angular's `@Inject` decorator used for?

The `@Inject` decorator is used to specify a dependency for injection when the type cannot be inferred.


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

@Injectable({
    providedIn: 'root'
})
export class ExampleService {
    constructor(@Inject(String) private value: string) { }
}
            

152. How do you implement Angular's `ngModel` directive for form control?

The `ngModel` directive is used for two-way data binding in forms.

<input [(ngModel)]="value" />
<p>Value: {{ value }}</p>

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent {
    value = 'Initial value';
}
            

153. What is Angular's `ng-template` and how is it used?

The `ng-template` directive defines a template that can be conditionally rendered.

<ng-template #template>
    </ng-template><ng-template #template><p>This is a template</p>
</ng-template>

<div *ngIf="showTemplate; else template">
    <p>Content when condition is true</p>
</div>
            

154. How do you use Angular's `ngOnChanges` lifecycle hook?

The `ngOnChanges` lifecycle hook is used to detect and act upon changes to input properties.


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

@Component({
    selector: 'app-example',
    template: '<p>{{ data }}</p>'
})
export class ExampleComponent implements OnChanges {
    @Input() data!: string;

    ngOnChanges(changes: SimpleChanges) {
        console.log(changes);
    }
}
            

155. What is Angular's `ngOnInit` lifecycle hook used for?

The `ngOnInit` lifecycle hook is used to perform component initialization after Angular has initialized all data-bound properties.


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

@Component({
    selector: 'app-example',
    template: '<p>Component initialized</p>'
})
export class ExampleComponent implements OnInit {
    ngOnInit() {
        console.log('Component initialized');
    }
}
            

156. How do you use Angular's `ngSwitch` directive?

The `ngSwitch` directive is used to conditionally display elements based on a switch expression.


<div [ngSwitch]="condition">
    <p *ngSwitchCase="'value1'">Case 1</p>
    <p *ngSwitchCase="'value2'">Case 2</p>
    <p *ngSwitchDefault>Default case</p>
</div>
            

157. How do you use Angular's `ngContainer`?

The `ngContainer` is used to group elements without adding extra DOM elements.

<ng-container *ngIf="isVisible">
    </ng-container><ng-container *ngIf="isVisible"><p>Content is visible</p>
</ng-container>
            

158. How do you use Angular's `ngFor` directive to iterate over an array?

The `ngFor` directive is used to repeat a block of HTML for each item in an array.


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

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent {
    items = ['Item 1', 'Item 2', 'Item 3'];
}
            

159. How do you use Angular's `ngModel` to bind form inputs to component properties?

The `ngModel` directive is used for two-way data binding with form inputs.

<input [(ngModel)]="inputValue" />
<p>Input value: {{ inputValue }}</p>

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent {
    inputValue = '';
}
            

160. How do you use Angular's `@NgModule` decorator to define a module?

The `@NgModule` decorator is used to define an Angular module, including its components, directives, and services.


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

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

 

Basic Angular Questions - Part 16

161. How do you use Angular's `ngIf` directive to conditionally render a block of HTML?

The `ngIf` directive is used to include or exclude a block of HTML based on a condition.


<div *ngIf="isVisible">
    <p>This content is conditionally rendered</p>
</div>

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent {
    isVisible = true;
}
            

162. What is the purpose of Angular's `ngOnInit` lifecycle hook?

The `ngOnInit` lifecycle hook is used to perform initialization logic after Angular has set all input properties.


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

@Component({
    selector: 'app-example',
    template: '<p>Component Initialized</p>'
})
export class ExampleComponent implements OnInit {
    ngOnInit() {
        console.log('Component Initialized');
    }
}
            

163. How can you use Angular's `ngClass` to dynamically apply CSS classes?

The `ngClass` directive can be used to dynamically add or remove CSS classes based on conditions.


<div [ngClass]="{'active': isActive, 'inactive': !isActive}">
    Content with dynamic classes
</div>

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent {
    isActive = true;
}
            

164. How do you create a custom Angular directive?

To create a custom directive, you use the `@Directive` decorator and implement the directive logic.


import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';

@Directive({
    selector: '[appHighlight]'
})
export class HighlightDirective {
    constructor(private el: ElementRef, private renderer: Renderer2) {}

    @HostListener('mouseenter') onMouseEnter() {
        this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow');
    }

    @HostListener('mouseleave') onMouseLeave() {
        this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'transparent');
    }
}
            

165. How do you use Angular's `ngFor` to iterate over an array of objects?

The `ngFor` directive is used to loop through an array and generate HTML for each item.


<ul>
    <li *ngFor="let item of items">{{ item.name }} - {{ item.value }}</li>
</ul>

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent {
    items = [
        { name: 'Item 1', value: 10 },
        { name: 'Item 2', value: 20 },
        { name: 'Item 3', value: 30 }
    ];
}
            

166. What is Angular's `@Input` decorator and how is it used?

The `@Input` decorator allows you to pass data from a parent component to a child component.


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

@Component({
    selector: 'app-child',
    template: '<p>{{ data }}</p>'
})
export class ChildComponent {
    @Input() data!: string;
}
            

167. How do you use Angular's `@Output` decorator to emit events from a component?

The `@Output` decorator is used to define an event that a component can emit to its parent component.


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

@Component({
    selector: 'app-button',
    template: '<button (click)="onClick()">Click me</button>'
})
export class ButtonComponent {
    @Output() clicked = new EventEmitter<void>();

    onClick() {
        this.clicked.emit();
    }
}
            

168. What is Angular's `@NgModule` decorator used for?

The `@NgModule` decorator defines an Angular module, including its components, directives, pipes, and services.


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

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

169. How do you bind an event in Angular?

Event binding is done using parentheses around the event name in the template.


<button (click)="handleClick()">Click me</button>

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent {
    handleClick() {
        console.log('Button clicked');
    }
}
            

170. What is Angular's `ng-container` and how is it used?

The `ng-container` is used to group elements without adding extra DOM elements.

<ng-container *ngIf="isVisible">
    </ng-container><ng-container *ngIf="isVisible"><p>Content is visible</p>
</ng-container>
            

171. How do you handle form validation in Angular?

Form validation is handled using `FormGroup` and `FormControl` with built-in or custom validators.


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

@Component({
    selector: 'app-form',
    template: '<form [formGroup]="form" (ngSubmit)="onSubmit()">...</form>'
})
export class FormComponent {
    form: FormGroup;

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

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

172. What is Angular's `@HostListener` decorator used for?

The `@HostListener` decorator is used to listen to events on the host element of a directive or component.


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

@Directive({
    selector: '[appClickTracker]'
})
export class ClickTrackerDirective {
    @HostListener('click', ['$event'])
    onClick(event: Event) {
        console.log('Element clicked', event);
    }
}
            

173. How do you use Angular's `HttpClient` to make HTTP requests?

The `HttpClient` service is used to make HTTP requests to a server and handle responses.


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

@Component({
    selector: 'app-data',
    template: '...',
})
export class DataComponent {
    constructor(private http: HttpClient) {}

    fetchData() {
        this.http.get('https://api.example.com/data').subscribe(data => {
            console.log(data);
        });
    }
}
            

174. What is the purpose of Angular's `ngOnDestroy` lifecycle hook?

The `ngOnDestroy` lifecycle hook is used to clean up resources, such as unsubscribing from observables or detaching event handlers, before a component is destroyed.


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

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent implements OnDestroy {
    private subscription: Subscription;

    constructor() {
        this.subscription = someObservable.subscribe();
    }

    ngOnDestroy() {
        this.subscription.unsubscribe();
    }
}
            

175. How do you use Angular's `ngModel` directive for two-way data binding?

The `ngModel` directive is used to bind form input values to component properties with two-way data binding.

<input [(ngModel)]="inputValue" />
<p>Input value: {{ inputValue }}</p>

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent {
    inputValue = '';
}
            

176. How do you use Angular's `@Injectable` decorator?

The `@Injectable` decorator marks a class as available for dependency injection.


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

@Injectable({
    providedIn: 'root'
})
export class ExampleService {
    getData() {
        return 'Data from service';
    }
}
            

177. How can you implement routing in an Angular application?

Routing in Angular is configured using the `RouterModule` and defining routes in a routing module.


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

const routes: Routes = [
    { path: 'home', component: HomeComponent },
    { path: 'about', component: AboutComponent },
    { path: '', redirectTo: '/home', pathMatch: 'full' }
];

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

178. How do you create a service in Angular and inject it into a component?

Create a service using `@Injectable`, then inject it into a component's constructor.


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

@Injectable({
    providedIn: 'root'
})
export class ExampleService {
    getData() {
        return 'Data from service';
    }
}

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent {
    constructor(private exampleService: ExampleService) {
        console.log(this.exampleService.getData());
    }
}
            

179. What are Angular modules and how do you create one?

Angular modules are classes with a `@NgModule` decorator that define a context for a set of components, directives, pipes, and services. You create a module using `@NgModule`.


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

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

180. How do you use Angular's `@Pipe` decorator to create a custom pipe?

The `@Pipe` decorator defines a custom pipe for transforming data in templates.


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

@Pipe({
    name: 'reverse'
})
export class ReversePipe implements PipeTransform {
    transform(value: string): string {
        return value.split('').reverse().join('');
    }
}
            

 

\

Basic Angular Questions - Part 17

181. How do you create a component in Angular?

Use the Angular CLI command `ng generate component ` to create a new component.


ng generate component my-component

// The command creates a folder with four files:
// my-component.component.ts
// my-component.component.html
// my-component.component.css
// my-component.component.spec.ts
            

182. What is Angular's `@Component` decorator used for?

The `@Component` decorator is used to define a component, including its metadata like selector, template, and style URLs.


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

@Component({
    selector: 'app-example',
    templateUrl: './example.component.html',
    styleUrls: ['./example.component.css']
})
export class ExampleComponent {
    // Component logic
}
            

183. How can you handle form submission in Angular?

Handle form submission by using the `(ngSubmit)` event in the template and handling it in the component.


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

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent {
    onSubmit() {
        console.log('Form submitted');
    }
}
            

184. How do you implement conditional rendering in Angular?

Use Angular's `*ngIf` directive to conditionally render elements based on a condition.


<div *ngIf="isVisible">
    <p>This content is conditionally rendered</p>
</div>

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent {
    isVisible = true;
}
            

185. What is Angular's `@NgModule` decorator and its purpose?

The `@NgModule` decorator defines an Angular module, including declarations, imports, providers, and bootstrap components.


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

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

186. How do you bind data to an Angular component's view?

Data binding is done using interpolation `{{}}`, property binding `[property]`, and event binding `(event)`.

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

<!-- Property Binding -->
<img [src]="imageUrl" />

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

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent {
    message = 'Hello, Angular!';
    imageUrl = 'https://example.com/image.jpg';

    handleClick() {
        console.log('Button clicked');
    }
}
            

187. How do you use Angular's `ngFor` directive to iterate over an array?

The `ngFor` directive is used to repeat an element for each item in an array.


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

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent {
    items = ['Item 1', 'Item 2', 'Item 3'];
}
            

188. What is the purpose of Angular's `@Injectable` decorator?

The `@Injectable` decorator marks a class as available for dependency injection.


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

@Injectable({
    providedIn: 'root'
})
export class ExampleService {
    getData() {
        return 'Data from service';
    }
}
            

189. How do you use Angular's `ngModel` for two-way data binding?

The `ngModel` directive enables two-way data binding by binding form input values to component properties.

<input [(ngModel)]="inputValue" />
<p>Input value: {{ inputValue }}</p>

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent {
    inputValue = '';
}
            

190. How do you define routes in Angular?

Routes are defined using the `RouterModule` and specifying route configurations in a routing module.


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

const routes: Routes = [
    { path: 'home', component: HomeComponent },
    { path: 'about', component: AboutComponent },
    { path: '', redirectTo: '/home', pathMatch: 'full' }
];

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

191. How do you use Angular's `@HostListener` to listen to events on the host element?

The `@HostListener` decorator allows you to listen to events on the host element of a directive or component.


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

@Directive({
    selector: '[appClickTracker]'
})
export class ClickTrackerDirective {
    @HostListener('click', ['$event'])
    onClick(event: Event) {
        console.log('Element clicked', event);
    }
}
            

192. What is the `@Pipe` decorator used for in Angular?

The `@Pipe` decorator defines a custom pipe for transforming data in templates.


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

@Pipe({
    name: 'reverse'
})
export class ReversePipe implements PipeTransform {
    transform(value: string): string {
        return value.split('').reverse().join('');
    }
}
            

193. How can you inject a service into a component in Angular?

Inject a service into a component by adding it to the component's constructor.


import { Component } from '@angular/core';
import { ExampleService } from './example.service';

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent {
    constructor(private exampleService: ExampleService) {
        console.log(this.exampleService.getData());
    }
}
            

194. What are Angular modules and how are they used?

Angular modules are classes annotated with `@NgModule` that group related components, directives, pipes, and services. They are used to organize an application into cohesive blocks.


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

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

195. How do you use Angular's `ngClass` directive for conditional styling?

The `ngClass` directive allows you to dynamically add or remove CSS classes based on conditions.


<div [ngClass]="{'active': isActive, 'inactive': !isActive}">
    Conditional styling
</div>

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent {
    isActive = true;
}
            

196. How do you handle user input in Angular forms?

Handle user input using Angular's forms module, either with template-driven forms or reactive forms.

<!-- Template-driven form -->
<form #myForm="ngForm" (ngSubmit)="onSubmit(myForm)">
    <input name="name" ngModel required />
    <button type="submit">Submit</button>
</form>

<!-- Reactive form -->
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent {
    form: FormGroup;

    constructor(private fb: FormBuilder) {
        this.form = this.fb.group({
            name: ['']
        });
    }

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

197. How do you create a pipe in Angular?

Create a custom pipe by defining a class with the `@Pipe` decorator and implementing the `PipeTransform` interface.


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

@Pipe({
    name: 'uppercase'
})
export class UppercasePipe implements PipeTransform {
    transform(value: string): string {
        return value.toUpperCase();
    }
}
            

198. What is the purpose of Angular's `ngOnInit` lifecycle hook?

The `ngOnInit` lifecycle hook is used to initialize component properties and perform any necessary setup after the component's data-bound properties have been initialized.


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

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent implements OnInit {
    ngOnInit() {
        console.log('Component initialized');
    }
}
            

199. How do you pass data from a parent component to a child component in Angular?

Pass data to a child component using `@Input` properties.


<!-- Parent component template -->
<app-child [data]="parentData"></app-child>

<!-- Child component -->
import { Component, Input } from '@angular/core';

@Component({
    selector: 'app-child',
    template: '...',
})
export class ChildComponent {
    @Input() data: any;
}
            

200. How do you use Angular's `@Output` decorator to emit events from a child component?

The `@Output` decorator is used to emit events from a child component to a parent component.


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

@Component({
    selector: 'app-child',
    template: '<button (click)="notify()">Notify</button>',
})
export class ChildComponent {
    @Output() notifyEvent = new EventEmitter<void>();

    notify() {
        this.notifyEvent.emit();
    }
}

// Parent component template
<app-child (notifyEvent)="onNotify()"></app-child>

@Component({
    selector: 'app-parent',
    template: '...',
})
export class ParentComponent {
    onNotify() {
        console.log('Notification received');
    }
}
            

Basic Angular Questions - Part 17

201. How do you create a component in Angular?

Use the Angular CLI command `ng generate component ` to create a new component.


ng generate component my-component

// The command creates a folder with four files:
// my-component.component.ts
// my-component.component.html
// my-component.component.css
// my-component.component.spec.ts
            

202. What is Angular's `@Component` decorator used for?

The `@Component` decorator is used to define a component, including its metadata like selector, template, and style URLs.


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

@Component({
    selector: 'app-example',
    templateUrl: './example.component.html',
    styleUrls: ['./example.component.css']
})
export class ExampleComponent {
    // Component logic
}
            

203. How can you handle form submission in Angular?

Handle form submission by using the `(ngSubmit)` event in the template and handling it in the component.


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

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent {
    onSubmit() {
        console.log('Form submitted');
    }
}
            

204. How do you implement conditional rendering in Angular?

Use Angular's `*ngIf` directive to conditionally render elements based on a condition.


<div *ngIf="isVisible">
    <p>This content is conditionally rendered</p>
</div>

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent {
    isVisible = true;
}
            

205. What is Angular's `@NgModule` decorator and its purpose?

The `@NgModule` decorator defines an Angular module, including declarations, imports, providers, and bootstrap components.


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

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

206. How do you bind data to an Angular component's view?

Data binding is done using interpolation `{{}}`, property binding `[property]`, and event binding `(event)`.

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

<!-- Property Binding -->
<img alt="" [src]="imageUrl" />

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

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent {
    message = 'Hello, Angular!';
    imageUrl = 'https://example.com/image.jpg';

    handleClick() {
        console.log('Button clicked');
    }
}
            

207. How do you use Angular's `ngFor` directive to iterate over an array?

The `ngFor` directive is used to repeat an element for each item in an array.


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

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent {
    items = ['Item 1', 'Item 2', 'Item 3'];
}
            

208. What is the purpose of Angular's `@Injectable` decorator?

The `@Injectable` decorator marks a class as available for dependency injection.


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

@Injectable({
    providedIn: 'root'
})
export class ExampleService {
    getData() {
        return 'Data from service';
    }
}
            

209. How do you use Angular's `ngModel` for two-way data binding?

The `ngModel` directive enables two-way data binding by binding form input values to component properties.

<input [(ngModel)]="inputValue" />
<p>Input value: {{ inputValue }}</p>

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent {
    inputValue = '';
}
            

210. How do you define routes in Angular?

Routes are defined using the `RouterModule` and specifying route configurations in a routing module.


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

const routes: Routes = [
    { path: 'home', component: HomeComponent },
    { path: 'about', component: AboutComponent },
    { path: '', redirectTo: '/home', pathMatch: 'full' }
];

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

211. How do you use Angular's `@HostListener` to listen to events on the host element?

The `@HostListener` decorator allows you to listen to events on the host element of a directive or component.


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

@Directive({
    selector: '[appClickTracker]'
})
export class ClickTrackerDirective {
    @HostListener('click', ['$event'])
    onClick(event: Event) {
        console.log('Element clicked', event);
    }
}
            

212. What is the `@Pipe` decorator used for in Angular?

The `@Pipe` decorator defines a custom pipe for transforming data in templates.


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

@Pipe({
    name: 'reverse'
})
export class ReversePipe implements PipeTransform {
    transform(value: string): string {
        return value.split('').reverse().join('');
    }
}
            

213. How can you inject a service into a component in Angular?

Inject a service into a component by adding it to the component's constructor.


import { Component } from '@angular/core';
import { ExampleService } from './example.service';

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent {
    constructor(private exampleService: ExampleService) {
        console.log(this.exampleService.getData());
    }
}
            

214. What are Angular modules and how are they used?

Angular modules are classes annotated with `@NgModule` that group related components, directives, pipes, and services. They are used to organize an application into cohesive blocks.


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

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

215. How do you use Angular's `ngClass` directive for conditional styling?

The `ngClass` directive allows you to dynamically add or remove CSS classes based on conditions.


<div [ngClass]="{'active': isActive, 'inactive': !isActive}">
    Conditional styling
</div>

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent {
    isActive = true;
}
            

216. How do you handle user input in Angular forms?

Handle user input using Angular's forms module, either with template-driven forms or reactive forms.

<!-- Template-driven form -->
<form #myForm="ngForm" (ngSubmit)="onSubmit(myForm)">
    <input name="name2" ngModel required />
    <button type="submit">Submit</button>
</form>

<!-- Reactive form -->
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent {
    form: FormGroup;

    constructor(private fb: FormBuilder) {
        this.form = this.fb.group({
            name: ['']
        });
    }

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

217. How do you create a pipe in Angular?

Create a custom pipe by defining a class with the `@Pipe` decorator and implementing the `PipeTransform` interface.


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

@Pipe({
    name: 'uppercase'
})
export class UppercasePipe implements PipeTransform {
    transform(value: string): string {
        return value.toUpperCase();
    }
}
            

218. What is the purpose of Angular's `ngOnInit` lifecycle hook?

The `ngOnInit` lifecycle hook is used to initialize component properties and perform any necessary setup after the component's data-bound properties have been initialized.


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

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent implements OnInit {
    ngOnInit() {
        console.log('Component initialized');
    }
}
            

219. How do you pass data from a parent component to a child component in Angular?

Pass data to a child component using `@Input` properties.


<!-- Parent component template -->
<app-child [data]="parentData"></app-child>

<!-- Child component -->
import { Component, Input } from '@angular/core';

@Component({
    selector: 'app-child',
    template: '...',
})
export class ChildComponent {
    @Input() data: any;
}
            

220. How do you use Angular's `@Output` decorator to emit events from a child component?

The `@Output` decorator is used to emit events from a child component to a parent component.


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

@Component({
    selector: 'app-child',
    template: '<button (click)="notify()">Notify</button>',
})
export class ChildComponent {
    @Output() notifyEvent = new EventEmitter<void>();

    notify() {
        this.notifyEvent.emit();
    }
}

// Parent component template
<app-child (notifyEvent)="onNotify()"></app-child>

@Component({
    selector: 'app-parent',
    template: '...',
})
export class ParentComponent {
    onNotify() {
        console.log('Notification received');
    }
}
            

 

Basic Angular Questions - Part 18

221. How do you create a module in Angular?

Create a module using the Angular CLI command `ng generate module ` or manually by defining a class with the `@NgModule` decorator.


ng generate module my-module

// Example of manually creating a module
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MyComponent } from './my.component';

@NgModule({
    declarations: [MyComponent],
    imports: [CommonModule],
    exports: [MyComponent]
})
export class MyModule { }
            

222. How do you set up routing in an Angular application?

Set up routing by defining routes in the `AppRoutingModule` and using the ` ` directive in the main template.


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

const routes: Routes = [
    { path: 'home', component: HomeComponent },
    { path: 'about', component: AboutComponent },
    { path: '', redirectTo: '/home', pathMatch: 'full' }
];

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

// In the main template
<router-outlet></router-outlet>
            

223. How do you implement lazy loading in Angular?

Implement lazy loading by configuring routes with the `loadChildren` property.


const routes: Routes = [
    { path: 'home', loadChildren: () => import('./home/home.module').then(m => m.HomeModule) },
    { path: '', redirectTo: '/home', pathMatch: 'full' }
];

// In home-routing.module.ts
const routes: Routes = [
    { path: '', component: HomeComponent }
];
            

224. What are Angular services and how are they used?

Angular services are classes that handle business logic and data access. They are used by injecting them into components or other services.


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

@Injectable({
    providedIn: 'root'
})
export class DataService {
    getData() {
        return 'Data from service';
    }
}

// Injecting service into a component
@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent {
    constructor(private dataService: DataService) {
        console.log(this.dataService.getData());
    }
}
            

225. How do you perform HTTP requests in Angular?

Perform HTTP requests using the `HttpClient` service.


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

@Injectable({
    providedIn: 'root'
})
export class DataService {
    constructor(private http: HttpClient) { }

    fetchData() {
        return this.http.get('https://api.example.com/data');
    }
}

// In the component
@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent {
    data: any;

    constructor(private dataService: DataService) {
        this.dataService.fetchData().subscribe(response => {
            this.data = response;
        });
    }
}
            

226. What is the purpose of Angular's `ngIf` directive?

The `ngIf` directive conditionally includes or excludes elements in the DOM based on an expression.


<div *ngIf="isVisible">
    <p>This content is visible</p>
</div>

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent {
    isVisible = true;
}
            

227. How do you use Angular's `ngFor` directive to loop over an array?

The `ngFor` directive repeats an element for each item in an array.


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

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent {
    items = ['Item 1', 'Item 2', 'Item 3'];
}
            

228. What is Angular's `@Output` decorator used for?

The `@Output` decorator is used to create custom events that components can emit to notify their parent components.


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

@Component({
    selector: 'app-child',
    template: '<button (click)="notify()">Notify</button>',
})
export class ChildComponent {
    @Output() notifyEvent = new EventEmitter<void>();

    notify() {
        this.notifyEvent.emit();
    }
}

// In the parent component
@Component({
    selector: 'app-parent',
    template: '...',
})
export class ParentComponent {
    onNotify() {
        console.log('Notification received');
    }
}
            

229. How do you use Angular's `@Input` decorator?

The `@Input` decorator is used to pass data from a parent component to a child component.


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

@Component({
    selector: 'app-child',
    template: '<p>{{ data }}</p>',
})
export class ChildComponent {
    @Input() data: string;
}

// In the parent component
@Component({
    selector: 'app-parent',
    template: '<app-child [data]="parentData"></app-child>',
})
export class ParentComponent {
    parentData = 'Data from parent';
}
            

230. What are Angular modules and why are they important?

Modules in Angular are used to organize an application into cohesive blocks. They help in managing and encapsulating components, services, directives, and pipes.


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

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

231. How do you handle form validation in Angular?

Form validation in Angular can be handled using built-in validators or custom validators in both template-driven and reactive forms.

<!-- Template-driven form -->
<form #myForm="ngForm" (ngSubmit)="onSubmit(myForm)">
    <input name="name3" ngModel required />
    <div *ngIf="myForm.submitted && !myForm.controls.name?.valid">
        Name is required
    </div>
    <button type="submit">Submit</button>
</form>

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

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent {
    form: FormGroup;

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

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

232. How do you create and use custom directives in Angular?

Create custom directives to extend the behavior of elements in your application.


import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';

@Directive({
    selector: '[appHighlight]'
})
export class HighlightDirective {
    constructor(private el: ElementRef, private renderer: Renderer2) { }

    @HostListener('mouseover') onMouseOver() {
        this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow');
    }

    @HostListener('mouseout') onMouseOut() {
        this.renderer.removeStyle(this.el.nativeElement, 'backgroundColor');
    }
}

// In the component template
<p appHighlight>Hover over me!</p>
            

233. What is Angular's change detection strategy and how can it be customized?

Angular's change detection strategy determines how and when the view updates. The default strategy is `CheckAlways`, but it can be customized to `OnPush` for performance optimization.


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

@Component({
    selector: 'app-example',
    template: '...',
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class ExampleComponent { }
            

234. How do you implement dependency injection in Angular?

Implement dependency injection by providing services in Angular modules or components and injecting them into constructors.


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

@Injectable({
    providedIn: 'root'
})
export class DataService {
    getData() {
        return 'Data from service';
    }
}

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent {
    constructor(private dataService: DataService) {
        console.log(this.dataService.getData());
    }
}
            

235. How do you use Angular's built-in pipes for formatting?

Angular provides built-in pipes for formatting data in templates, such as `DatePipe`, `CurrencyPipe`, and `DecimalPipe`.


<p>{{ today | date:'shortDate' }}</p>
<p>{{ amount | currency:'USD' }}</p>
<p>{{ number | number:'1.2-2' }}</p>

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent {
    today = new Date();
    amount = 1234.56;
    number = 1234.5678;
}
            

236. How do you manage state in an Angular application?

State management in Angular can be handled using services, or more advanced solutions like NgRx for large applications.


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

@Injectable({
    providedIn: 'root'
})
export class StateService {
    private state = new BehaviorSubject<any>({});
    state$ = this.state.asObservable();

    setState(newState: any) {
        this.state.next(newState);
    }
}

// In the component
@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent {
    state$ = this.stateService.state$;

    constructor(private stateService: StateService) { }

    updateState() {
        this.stateService.setState({ key: 'value' });
    }
}
            

237. How do you handle errors in Angular HTTP requests?

Handle errors in HTTP requests by using the `catchError` operator from RxJS and handling them in the service.


import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';

@Injectable({
    providedIn: 'root'
})
export class DataService {
    constructor(private http: HttpClient) { }

    fetchData() {
        return this.http.get('https://api.example.com/data').pipe(
            catchError(error => {
                console.error('Error occurred:', error);
                return throwError(error);
            })
        );
    }
}
            

238. How do you use Angular's `ngOnDestroy` lifecycle hook?

The `ngOnDestroy` lifecycle hook is used to perform cleanup before the component is destroyed.


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

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent implements OnDestroy {
    private subscription: Subscription;

    ngOnDestroy() {
        if (this.subscription) {
            this.subscription.unsubscribe();
        }
    }
}
            

239. How do you use Angular's `@HostListener` decorator?

The `@HostListener` decorator allows you to listen to events on the host element of a directive or component.


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

@Directive({
    selector: '[appClickTracker]'
})
export class ClickTrackerDirective {
    @HostListener('click', ['$event'])
    onClick(event: MouseEvent) {
        console.log('Element clicked:', event);
    }
}
            

240. How do you use Angular's `ngStyle` directive for dynamic styling?

The `ngStyle` directive allows you to set multiple inline styles dynamically based on an expression.


<div [ngStyle]="{'color': isRed ? 'red' : 'blue', 'font-size': fontSize + 'px'}">
    Dynamic styling
</div>

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent {
    isRed = true;
    fontSize = 16;
}
            

 

Basic Angular Questions - Part 19

241. How do you use Angular's `ngClass` directive?

The `ngClass` directive allows you to dynamically add or remove CSS classes based on an expression.


<div [ngClass]="{'active': isActive, 'disabled': isDisabled}">
    Dynamic classes
</div>

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent {
    isActive = true;
    isDisabled = false;
}
            

242. What are Angular guards and how do you use them?

Angular guards are used to protect routes and control access. They can be implemented using interfaces such as `CanActivate`, `CanDeactivate`, `Resolve`, and `CanLoad`.


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

@Injectable({
    providedIn: 'root'
})
export class AuthGuard implements CanActivate {
    constructor(private router: Router) { }

    canActivate(): boolean {
        const isAuthenticated = false; // Replace with actual authentication check
        if (isAuthenticated) {
            return true;
        } else {
            this.router.navigate(['/login']);
            return false;
        }
    }
}

// In app-routing.module.ts
const routes: Routes = [
    { path: 'protected', component: ProtectedComponent, canActivate: [AuthGuard] }
];
            

243. How do you use Angular's `@ContentChild` and `@ContentChildren` decorators?

The `@ContentChild` and `@ContentChildren` decorators are used to access content projected into a component using `ng-content`.


import { Component, ContentChild, ContentChildren, QueryList, AfterContentInit } from '@angular/core';
import { ElementRef } from '@angular/core';

@Component({
    selector: 'app-parent',
    template: '<ng-content></ng-content>',
})
export class ParentComponent implements AfterContentInit {
    @ContentChild('header') header: ElementRef;
    @ContentChildren('item') items: QueryList<ElementRef>;

    ngAfterContentInit() {
        console.log(this.header.nativeElement.textContent);
        this.items.forEach(item => console.log(item.nativeElement.textContent));
    }
}

// In the parent component template
<app-parent>
    </app-parent><app-parent><h1 #header>Header</h1>
    <p #item>Item 1</p>
    <p #item>Item 2</p>
</app-parent>
            

244. What is Angular's `Renderer2` and how is it used?

`Renderer2` is an Angular service used to manipulate the DOM in a way that is safe and compatible with different platforms.


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

@Component({
    selector: 'app-example',
    template: '<div #myDiv></div>',
})
export class ExampleComponent implements AfterViewInit {
    constructor(private renderer: Renderer2, private el: ElementRef) { }

    ngAfterViewInit() {
        const div = this.el.nativeElement.querySelector('div');
        this.renderer.setStyle(div, 'color', 'red');
    }
}
            

245. How do you use Angular's `FormArray` for dynamic form controls?

`FormArray` is used to manage an array of form controls or form groups. It allows dynamic addition and removal of form elements.


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

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent {
    form: FormGroup;

    constructor(private fb: FormBuilder) {
        this.form = this.fb.group({
            items: this.fb.array([])
        });
    }

    get items() {
        return this.form.get('items') as FormArray;
    }

    addItem() {
        this.items.push(this.fb.control(''));
    }

    removeItem(index: number) {
        this.items.removeAt(index);
    }
}
            

246. How do you use Angular's `NgModule` imports and exports?

Use `NgModule` imports to include other modules in your module and exports to make components, directives, or pipes available outside the module.


@NgModule({
    imports: [CommonModule, FormsModule],
    declarations: [MyComponent],
    exports: [MyComponent]
})
export class MyModule { }
            

247. What is Angular's `@ViewChild` and `@ViewChildren` decorators used for?

`@ViewChild` and `@ViewChildren` are used to access elements or components within the component's view.


import { Component, ViewChild, ViewChildren, QueryList, ElementRef, AfterViewInit } from '@angular/core';

@Component({
    selector: 'app-example',
    template: `
        <p #paragraph>Paragraph 1</p>
        <p #paragraph>Paragraph 2</p>
    `,
})
export class ExampleComponent implements AfterViewInit {
    @ViewChild('paragraph') paragraph: ElementRef;
    @ViewChildren('paragraph') paragraphs: QueryList<ElementRef>;

    ngAfterViewInit() {
        console.log(this.paragraph.nativeElement.textContent);
        this.paragraphs.forEach(p => console.log(p.nativeElement.textContent));
    }
}
            

248. How do you create and use Angular pipes?

Angular pipes transform data in templates. You can create custom pipes by implementing the `PipeTransform` interface.


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

@Pipe({
    name: 'reverse'
})
export class ReversePipe implements PipeTransform {
    transform(value: string): string {
        return value.split('').reverse().join('');
    }
}

// In the component template
<p>{{ 'Hello' | reverse }}</p>
            

249. What are Angular's lifecycle hooks and how are they used?

Lifecycle hooks are methods that Angular calls at different stages of a component's lifecycle, such as `ngOnInit`, `ngOnChanges`, `ngOnDestroy`, etc.


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

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent implements OnInit, OnDestroy {
    ngOnInit() {
        console.log('Component initialized');
    }

    ngOnDestroy() {
        console.log('Component destroyed');
    }
}
            

250. How do you use Angular's `ChangeDetectorRef` service?

The `ChangeDetectorRef` service is used to manually trigger change detection.


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

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent {
    constructor(private cdr: ChangeDetectorRef) { }

    triggerChangeDetection() {
        this.cdr.detectChanges();
    }
}
            

251. How do you handle form validation in Angular?

Form validation in Angular is handled using validators on form controls or form groups. Validators can be synchronous or asynchronous.


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

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent {
    form: FormGroup;

    constructor(private fb: FormBuilder) {
        this.form = this.fb.group({
            name: ['', [Validators.required, Validators.minLength(3)]]
        });
    }

    get name() {
        return this.form.get('name');
    }

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

252. How do you use Angular's `HttpInterceptor` for HTTP requests?

Use `HttpInterceptor` to intercept HTTP requests and responses for tasks such as adding headers or logging.


import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const authReq = req.clone({
            headers: req.headers.set('Authorization', 'Bearer token')
        });
        return next.handle(authReq);
    }
}

// In app.module.ts
providers: [
    { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }
]
            

253. How do you use Angular's `@Input` and `@Output` decorators?

The `@Input` decorator allows a component to receive data from its parent, and the `@Output` decorator allows a component to emit events to its parent.


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

@Component({
    selector: 'app-child',
    template: `<button (click)="notify()">Notify</button>`,
})
export class ChildComponent {
    @Input() message: string;
    @Output() notify: EventEmitter<string> = new EventEmitter<string>();

    notifyParent() {
        this.notify.emit('Hello from child');
    }
}

@Component({
    selector: 'app-parent',
    template: `<app-child [message]="parentMessage" (notify)="onNotify($event)"></app-child>`,
})
export class ParentComponent {
    parentMessage = 'Message from parent';

    onNotify(message: string) {
        console.log(message);
    }
}
            

254. How do you create a lazy-loaded module in Angular?

Create a lazy-loaded module by using the `loadChildren` property in the routing configuration.


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

255. How do you use Angular's `NgModule` for modular architecture?

Use `NgModule` to organize an application into cohesive blocks of functionality, which helps with code organization and reusability.


@NgModule({
    declarations: [Component1, Component2],
    imports: [CommonModule, FormsModule],
    exports: [Component1]
})
export class SharedModule { }
            

256. How do you use Angular's `ViewEncapsulation`?

`ViewEncapsulation` controls how styles are encapsulated within a component. Options include `Emulated`, `Native`, and `None`.


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

@Component({
    selector: 'app-example',
    template: '...',
    styles: [`p { color: red; }`],
    encapsulation: ViewEncapsulation.None
})
export class ExampleComponent { }
            

257. How do you use Angular's `async` pipe?

The `async` pipe automatically subscribes to an observable or promise and returns the latest value.


@Component({
    selector: 'app-example',
    template: `<p>{{ data$ | async }}</p>`,
})
export class ExampleComponent {
    data$ = this.dataService.getData();

    constructor(private dataService: DataService) { }
}
            

258. How do you use Angular's `ngFor` directive?

The `ngFor` directive is used to repeat a block of HTML for each item in an array or list.


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

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent {
    items = ['Item 1', 'Item 2', 'Item 3'];
}
            

259. How do you use Angular's `ngIf` directive?

The `ngIf` directive conditionally includes or excludes a block of HTML based on an expression.


<p *ngIf="isVisible">Visible content</p>

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent {
    isVisible = true;
}
            

260. How do you use Angular's `ngSwitch` directive?

The `ngSwitch` directive allows you to conditionally include one of multiple elements based on a value.


<div [ngSwitch]="selectedValue">
    <p *ngSwitchCase="'A'">Case A</p>
    <p *ngSwitchCase="'B'">Case B</p>
    <p *ngSwitchDefault>Default case</p>
</div>

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent {
    selectedValue = 'A';
}
            

 

Basic Angular Questions - Part 20

261. How do you use Angular's `@Injectable` decorator?

The `@Injectable` decorator marks a class as available to be provided and injected as a dependency.


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

@Injectable({
    providedIn: 'root',
})
export class ExampleService {
    constructor() { }
}
            

262. What is Angular's `NgZone` and how do you use it?

`NgZone` is used to execute code inside or outside Angular's zone to control change detection.


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

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent {
    constructor(private ngZone: NgZone) { }

    runOutsideAngular() {
        this.ngZone.runOutsideAngular(() => {
            // Code here will not trigger Angular's change detection
        });
    }
}
            

263. How do you use Angular's `@HostListener` decorator?

The `@HostListener` decorator allows you to listen to events on the host element of a directive or component.


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

@Directive({
    selector: '[appHover]'
})
export class HoverDirective {
    @HostListener('mouseenter') onMouseEnter() {
        console.log('Mouse entered');
    }

    @HostListener('mouseleave') onMouseLeave() {
        console.log('Mouse left');
    }
}
            

264. How do you use Angular's `@ViewEncapsulation`?

`@ViewEncapsulation` controls how styles are applied to the component's view. It can be `Emulated`, `Native`, or `None`.


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

@Component({
    selector: 'app-example',
    template: `<p>Styled text</p>`,
    styles: [`p { color: green; }`],
    encapsulation: ViewEncapsulation.Emulated
})
export class ExampleComponent { }
            

265. What is Angular's `Renderer2` and how is it used?

`Renderer2` is a service for safely manipulating the DOM.


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

@Component({
    selector: 'app-example',
    template: `<div #myDiv></div>`,
})
export class ExampleComponent implements OnInit {
    constructor(private renderer: Renderer2, private el: ElementRef) { }

    ngOnInit() {
        const div = this.el.nativeElement.querySelector('div');
        this.renderer.setStyle(div, 'color', 'blue');
    }
}
            

266. How do you use Angular's `HttpClient` for making HTTP requests?

`HttpClient` is used to make HTTP requests and handle responses.


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

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent {
    constructor(private http: HttpClient) { }

    fetchData() {
        this.http.get('https://api.example.com/data').subscribe(data => {
            console.log(data);
        });
    }
}
            

267. How do you use Angular's `NgModule` for organizing code?

`NgModule` is used to organize an Angular application into cohesive blocks of functionality.


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

268. How do you create a custom Angular directive?

Create a custom directive to modify the behavior or appearance of elements.


import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';

@Directive({
    selector: '[appHighlight]'
})
export class HighlightDirective {
    constructor(private el: ElementRef, private renderer: Renderer2) { }

    @HostListener('mouseenter') onMouseEnter() {
        this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow');
    }

    @HostListener('mouseleave') onMouseLeave() {
        this.renderer.removeStyle(this.el.nativeElement, 'backgroundColor');
    }
}
            

269. What are Angular's `ngOnInit` and `ngOnChanges` lifecycle hooks used for?

`ngOnInit` is used for component initialization, while `ngOnChanges` is used to respond to changes in input properties.


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

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent implements OnInit, OnChanges {
    @Input() data: string;

    ngOnInit() {
        console.log('Component initialized');
    }

    ngOnChanges(changes: SimpleChanges) {
        console.log('Input properties changed', changes);
    }
}
            

270. How do you use Angular's `FormBuilder` for creating reactive forms?

`FormBuilder` simplifies the creation of reactive forms.


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

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent {
    form: FormGroup;

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

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

271. How do you use Angular's `@Input` and `@Output` decorators?

`@Input` allows a parent component to pass data to a child component, and `@Output` allows a child component to emit events to a parent component.


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

@Component({
    selector: 'app-child',
    template: `<button (click)="notify()">Notify</button>`,
})
export class ChildComponent {
    @Input() childData: string;
    @Output() notify: EventEmitter<string> = new EventEmitter<string>();

    notifyParent() {
        this.notify.emit('Data from child');
    }
}

@Component({
    selector: 'app-parent',
    template: `<app-child [childData]="parentData" (notify)="handleNotify($event)"></app-child>`,
})
export class ParentComponent {
    parentData = 'Data from parent';

    handleNotify(data: string) {
        console.log(data);
    }
}
            

272. How do you handle navigation and routing in Angular?

Use Angular's Router module to define routes and navigate between different views.


import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

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

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

273. How do you use Angular's `@NgModule` to create a feature module?

Create a feature module to encapsulate related components, directives, and services.


@NgModule({
    declarations: [FeatureComponent],
    imports: [CommonModule, SharedModule],
    exports: [FeatureComponent]
})
export class FeatureModule { }
            

274. How do you use Angular's `@ViewChild` and `@ContentChild` decorators?

`@ViewChild` allows you to access a child component or directive, and `@ContentChild` allows you to access projected content.


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

@Component({
    selector: 'app-example',
    template: `<p #paragraph>Content</p><ng-content></ng-content>`,
})
export class ExampleComponent {
    @ViewChild('paragraph') paragraph: ElementRef;
    @ContentChild('content') content: ElementRef;

    ngAfterViewInit() {
        console.log(this.paragraph.nativeElement.textContent);
    }

    ngAfterContentInit() {
        console.log(this.content.nativeElement.textContent);
    }
}
            

275. How do you use Angular's `ngStyle` directive?

`ngStyle` is used to dynamically set multiple inline styles for an element.


@Component({
    selector: 'app-example',
    template: `<div [ngStyle]="{'color': color, 'font-size': fontSize}">Styled text</div>`,
})
export class ExampleComponent {
    color = 'blue';
    fontSize = '20px';
}
            

276. How do you use Angular's `ngClass` directive?

`ngClass` is used to dynamically add or remove CSS classes from an element based on conditions.


@Component({
    selector: 'app-example',
    template: `<div [ngClass]="{'active': isActive, 'inactive': !isActive}">Classy div</div>`,
})
export class ExampleComponent {
    isActive = true;
}
            

277. How do you use Angular's `ngFor` directive to iterate over objects?

`ngFor` can be used to iterate over objects by using the `keyvalue` pipe.


<ul>
    <li *ngFor="let entry of object | keyvalue">{{ entry.key }}: {{ entry.value }}</li>
</ul>

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent {
    object = { name: 'John', age: 30 };
}
            

278. How do you use Angular's `ngTemplateOutlet` directive?

`ngTemplateOutlet` is used to dynamically insert an ` ` into the DOM.

<ng-template #template>
    </ng-template><ng-template #template><p>Template content</p>
</ng-template>

<div [ngTemplateOutlet]="template"></div>

@Component({
    selector: 'app-example',
    template: '...',
})
export class ExampleComponent { }
            

279. How do you use Angular's `ngContent` directive?

`ngContent` is used to project content into a component's template.


@Component({
    selector: 'app-example',
    template: `<ng-content></ng-content>`,
})
export class ExampleComponent { }

@Component({
    selector: 'app-parent',
    template: `<app-example></app-example><app-example><p>Projected content</p></app-example>`,
})
export class ParentComponent { }
            

280. How do you use Angular's `@HostBinding` decorator?

`@HostBinding` is used to bind properties of the host element to component or directive properties.


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

@Directive({
    selector: '[appHighlight]'
})
export class HighlightDirective {
    @HostBinding('class.highlighted') isHighlighted = true;
}
            

281. What is Angular?

Angular is a TypeScript-based, open-source single-page application (SPA) framework developed by Google. It provides components, dependency injection, routing, forms, and RxJS-based reactivity.

282. What is the difference between AngularJS and Angular?

AngularJS (1.x) is JavaScript-based and uses controllers and $scope. Angular (2+) is TypeScript-based, component-driven, and uses a modern change-detection and DI system.

283. What is a component in Angular?

A component is a UI building block defined by a TypeScript class with an @Component decorator that specifies selector, template, and styles.

@Component({
  selector: 'app-hello',
  template: '<h1>Hello {{name}}</h1>'
})
export class HelloComponent {
  name = 'Angular';
}

284. What are the types of data binding in Angular?

Interpolation {{ }}, property binding [prop], event binding (event), and two-way binding [(ngModel)].

285. What is a directive?

A directive is a class that adds behavior to elements. Structural directives change DOM structure (*ngIf, *ngFor); attribute directives change appearance/behavior (ngClass, ngStyle).

286. What is a pipe?

A pipe transforms data in templates. Examples: DatePipe, UpperCasePipe, and custom pipes created with @Pipe.

<p>{{ today | date:'short' }}</p>

287. What is a service in Angular?

A service is a reusable class (often marked @Injectable) that encapsulates business logic and data access, shared across components.

288. What is dependency injection (DI)?

DI is a design pattern where dependencies are provided to a class rather than created inside it. Angular's injector supplies services to components via constructor parameters.

constructor(private userService: UserService) {}

289. Name common Angular lifecycle hooks.

ngOnInit, ngOnChanges, ngAfterViewInit, ngOnDestroy. They run at specific points in a component's life.

290. What is an Angular module (NgModule)?

An @NgModule groups related components, directives, pipes, and services. AppModule bootstraps the application.

291. How does routing work in Angular?

Define routes with RouterModule.forRoot(routes), navigate with routerLink, and render views via <router-outlet>.

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

292. What are template-driven and reactive forms?

Template-driven forms use ngModel and directives in the template. Reactive forms build a form model in TypeScript using FormGroup/FormControl.

293. What is an Observable in RxJS?

An Observable is a lazy stream of values over time. Components subscribe to receive emissions and unsubscribe to avoid leaks.

this.http.get('/api/users').subscribe(data => this.users = data);

294. What is change detection in Angular?

Angular checks component state and updates the DOM. Default strategy checks the whole tree; OnPush checks only when inputs change or events fire, improving performance.

295. What are common Angular CLI commands?

ng new, ng serve, ng generate component, ng build, ng test.

296. How do you use interpolation?

Interpolation displays component property values in the template using double curly braces.

<p>Welcome, {{ userName }}!</p>

297. How do *ngIf and *ngFor work?

*ngIf conditionally renders an element; *ngFor repeats an element for each item in a collection.

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

298. How do you make HTTP requests in Angular?

Import HttpClientModule and inject HttpClient to call REST APIs returning Observables.

this.http.get<User[]>('/api/users').subscribe(u => this.users = u);

299. How are Angular apps tested?

Use Jasmine/Karma by default. TestBed configures a testing module; component specs verify rendering and behavior.

TestBed.configureTestingModule({ declarations: [AppComponent] });

300. How is an Angular application bootstrapped?

main.ts calls platformBrowserDynamic().bootstrapModule(AppModule), which starts the root component.

Intermediate 380 questions

Dynamic reactive forms with FormArray, advanced RxJS patterns, hierarchical DI, dynamic components, custom directives and pipes, and change detection strategies. Original page

Angular Framework — Intermediate Concepts & Advanced Patterns (Part 1).

Guía de preguntas y respuestas de nivel intermedio sobre Angular: formularios reactivos dinámicos (FormArray), operadores y patrones avanzados con RxJS, inyección de dependencias jerárquica (providedIn, @Optional, @Self, @SkipSelf), componentes dinámicos (ViewContainerRef, createComponent), directivas personalizadas, pipes puros e impuros, estrategias de detección de cambios (OnPush), ciclo de vida, enrutamiento con guards y resolvers, y comunicación entre componentes.

301. How do you create a dynamic form in Angular using `FormArray`?

`FormArray` is used to manage a collection of form controls in Angular reactive forms.


import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';

@Component({
    selector: 'app-dynamic-form',
    template: `
        <form [formGroup]="form">
            <div formArrayName="items">
                <div *ngFor="let item of items.controls; let i = index">
                    <input [formControlName]="i" />
                </div>
            </div>
            <button (click)="addItem()">Add Item</button>
        </form>
    `,
})
export class DynamicFormComponent {
    form: FormGroup;

    constructor(private fb: FormBuilder) {
        this.form = this.fb.group({
            items: this.fb.array([])
        });
    }

    get items() {
        return this.form.get('items') as FormArray;
    }

    addItem() {
        this.items.push(this.fb.control(''));
    }
}
            

302. How do you implement lazy loading in Angular?

Lazy loading is implemented using Angular's routing module by defining routes with a loadChildren property.


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

303. How can you handle HTTP errors in Angular?

HTTP errors can be handled using Angular's `HttpInterceptor` to catch and process HTTP errors globally.


import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpErrorResponse } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler) {
        return next.handle(req).pipe(
            catchError((error: HttpErrorResponse) => {
                // Handle error
                console.error('HTTP Error:', error);
                return throwError(error);
            })
        );
    }
}
            

304. How do you use Angular's `ContentChildren` to query for content?

`@ContentChildren` allows querying of projected content in Angular.


import { Component, ContentChildren, QueryList, AfterContentInit } from '@angular/core';
import { ChildComponent } from './child.component';

@Component({
    selector: 'app-parent',
    template: `
        <ng-content></ng-content>
    `,
})
export class ParentComponent implements AfterContentInit {
    @ContentChildren(ChildComponent) children: QueryList<ChildComponent>;

    ngAfterContentInit() {
        console.log(this.children.toArray());
    }
}
            

305. How do you use Angular's `ngIf` with `else` syntax?

The `ngIf` directive can be used with `else` to conditionally display alternate content.


@Component({
    selector: 'app-example',
    template: `
        <div *ngIf="isVisible; else notVisible">Content is visible</div>
        <ng-template #notVisible>Content is not visible</ng-template>
    `,
})
export class ExampleComponent {
    isVisible = true;
}
            

306. How do you use Angular's `ngFor` with `trackBy` function?

The `trackBy` function is used to optimize the rendering of lists by tracking changes to items in the list.


@Component({
    selector: 'app-example',
    template: `
        <div *ngFor="let item of items; trackBy: trackById">{{ item.name }}</div>
    `,
})
export class ExampleComponent {
    items = [{ id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }];

    trackById(index: number, item: any) {
        return item.id;
    }
}
            

307. How do you create a custom Angular pipe?

A custom pipe is created to transform data in the template.


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

@Pipe({
    name: 'reverse'
})
export class ReversePipe implements PipeTransform {
    transform(value: string): string {
        return value.split('').reverse().join('');
    }
}
            

308. How do you use Angular's `@HostListener` decorator?

`@HostListener` allows listening to events on the host element of a directive or component.


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

@Directive({
    selector: '[appHover]'
})
export class HoverDirective {
    @HostListener('mouseenter') onMouseEnter() {
        console.log('Mouse entered');
    }

    @HostListener('mouseleave') onMouseLeave() {
        console.log('Mouse left');
    }
}
            

309. How do you handle form validation in Angular?

Form validation can be handled using Angular's reactive forms and built-in validators.


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

@Component({
    selector: 'app-form',
    template: `
        <form [formGroup]="form" (ngSubmit)="onSubmit()">
            <input formControlName="name" />
            <div *ngIf="form.controls['name'].invalid">Name is required</div>
            <button type="submit">Submit</button>
        </form>
    `,
})
export class FormComponent {
    form: FormGroup;

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

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

310. How do you use Angular's `@Inject` decorator?

The `@Inject` decorator is used to specify the provider to be injected into a class.


import { Injectable, Inject } from '@angular/core';
import { API_URL } from './tokens';

@Injectable({
    providedIn: 'root'
})
export class ApiService {
    constructor(@Inject(API_URL) private apiUrl: string) { }
}
            

311. How do you implement custom error handling in Angular services?

Custom error handling can be implemented using Angular's `HttpInterceptor` to catch and handle HTTP errors.


import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpErrorResponse } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';

@Injectable()
export class CustomErrorInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler) {
        return next.handle(req).pipe(
            catchError((error: HttpErrorResponse) => {
                // Custom error handling logic
                console.error('An error occurred:', error.message);
                return throwError(error);
            })
        );
    }
}
            

312. How do you create a reusable Angular component?

A reusable component is created by defining it with a selector and providing inputs and outputs.


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

@Component({
    selector: 'app-reusable',
    template: `
        <button (click)="onClick()">Click me</button>
    `,
})
export class ReusableComponent {
    @Input() label: string;
    @Output() clicked = new EventEmitter<void>();

    onClick() {
        this.clicked.emit();
    }
}
            

313. How do you use Angular's Dependency Injection system?

Dependency Injection is used to inject services or other dependencies into components or services.


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

@Injectable({
    providedIn: 'root'
})
export class DataService {
    getData() {
        return ['Item 1', 'Item 2'];
    }
}
            

314. How do you manage application state in Angular?

Application state can be managed using services, or state management libraries like NgRx or Akita.


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

@Injectable({
    providedIn: 'root'
})
export class StateService {
    private state = new BehaviorSubject<any>({});
    state$ = this.state.asObservable();

    setState(newState: any) {
        this.state.next(newState);
    }
}
            

315. How do you configure Angular's build and deployment settings?

Build and deployment settings are configured in the `angular.json` file.


{
    "projects": {
        "my-app": {
            "architect": {
                "build": {
                    "options": {
                        "outputPath": "dist/my-app",
                        "index": "src/index.html",
                        "main": "src/main.ts",
                        "tsConfig": "tsconfig.app.json"
                    }
                }
            }
        }
    }
}
            

316. How do you implement Angular route guards?

Route guards are used to control access to routes based on conditions.


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

@Injectable({
    providedIn: 'root'
})
export class AuthGuard implements CanActivate {
    constructor(private router: Router) { }

    canActivate(): boolean {
        // Check authentication status
        const isAuthenticated = false;
        if (!isAuthenticated) {
            this.router.navigate(['/login']);
            return false;
        }
        return true;
    }
}
            

317. How do you use Angular's `HttpClient` for making HTTP requests?

`HttpClient` is used for making HTTP requests to a backend API.


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

@Injectable({
    providedIn: 'root'
})
export class ApiService {
    constructor(private http: HttpClient) { }

    getData() {
        return this.http.get('https://api.example.com/data');
    }
}
            

318. How do you create and use Angular services?

Services are used to share data and logic across multiple components.


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

@Injectable({
    providedIn: 'root'
})
export class DataService {
    getData() {
        return ['Item 1', 'Item 2'];
    }
}
            

319. How do you use Angular's `@Input` and `@Output` decorators?

`@Input` is used to pass data to a child component, and `@Output` is used to emit events from a child component.


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

@Component({
    selector: 'app-child',
    template: `<button (click)="notify()">Notify</button>`,
})
export class ChildComponent {
    @Input() data: string;
    @Output() notifyEvent = new EventEmitter<string>();

    notify() {
        this.notifyEvent.emit('Notification from child');
    }
}
            

320. How do you use Angular's `@ViewChild` decorator?

`@ViewChild` is used to access a child component or DOM element from the parent component.


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

@Component({
    selector: 'app-parent',
    template: `<p #paragraph>Paragraph</p>`,
})
export class ParentComponent implements AfterViewInit {
    @ViewChild('paragraph') paragraph: ElementRef;

    ngAfterViewInit() {
        console.log(this.paragraph.nativeElement.textContent);
    }
}
            

Intermediate Angular Questions - Part 2

321. How do you use Angular's `ngSwitch` directive?

The `ngSwitch` directive is used to conditionally display one of several elements based on the value of an expression.


@Component({
    selector: 'app-switch',
    template: `
        <div [ngSwitch]="value">
            <p *ngSwitchCase="'A'">Case A</p>
            <p *ngSwitchCase="'B'">Case B</p>
            <p *ngSwitchDefault>Default case</p>
        </div>
    `,
})
export class SwitchComponent {
    value = 'A';
}
            

322. How do you implement a custom Angular directive?

Custom directives can be created to modify the behavior or appearance of elements.


import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';

@Directive({
    selector: '[appHighlight]'
})
export class HighlightDirective {
    constructor(private el: ElementRef, private renderer: Renderer2) { }

    @HostListener('mouseenter') onMouseEnter() {
        this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow');
    }

    @HostListener('mouseleave') onMouseLeave() {
        this.renderer.removeStyle(this.el.nativeElement, 'backgroundColor');
    }
}
            

323. How do you configure Angular's HTTP interceptors?

HTTP interceptors are used to modify HTTP requests and responses.


import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { ErrorInterceptor } from './error.interceptor';

@NgModule({
    providers: [
        { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }
    ]
})
export class AppModule { }
            

324. How do you use Angular's `@HostBinding` decorator?

The `@HostBinding` decorator binds a property of the host element to a property of the directive or component.


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

@Directive({
    selector: '[appClass]'
})
export class ClassDirective {
    @HostBinding('class.active') isActive = true;
}
            

325. How do you use Angular's `@ViewChildren` decorator?

The `@ViewChildren` decorator is used to query for multiple elements or directives in the template.


import { Component, ViewChildren, QueryList, AfterViewInit } from '@angular/core';
import { ChildComponent } from './child.component';

@Component({
    selector: 'app-parent',
    template: `
        <app-child *ngFor="let child of children"></app-child>
    `,
})
export class ParentComponent implements AfterViewInit {
    @ViewChildren(ChildComponent) childComponents: QueryList<ChildComponent>;

    ngAfterViewInit() {
        console.log(this.childComponents.toArray());
    }
}
            

326. How do you handle asynchronous operations in Angular components?

Asynchronous operations can be handled using RxJS observables and operators.


import { Component, OnInit } from '@angular/core';
import { ApiService } from './api.service';

@Component({
    selector: 'app-data',
    template: `
        <div *ngIf="data$ | async as data">
            {{ data | json }}
        </div>
    `,
})
export class DataComponent implements OnInit {
    data$ = this.apiService.getData();

    constructor(private apiService: ApiService) { }

    ngOnInit() { }
}
            

327. How do you use Angular's `@ContentChild` decorator?

The `@ContentChild` decorator allows querying for a single projected content element.


import { Component, ContentChild, AfterContentInit } from '@angular/core';
import { ChildComponent } from './child.component';

@Component({
    selector: 'app-parent',
    template: `<ng-content></ng-content>`,
})
export class ParentComponent implements AfterContentInit {
    @ContentChild(ChildComponent) child: ChildComponent;

    ngAfterContentInit() {
        console.log(this.child);
    }
}
            

328. How do you use Angular's `ngClass` directive?

The `ngClass` directive is used to add or remove CSS classes dynamically.


@Component({
    selector: 'app-example',
    template: `
        <div [ngClass]="{'active': isActive, 'inactive': !isActive}">
            Conditional classes
        </div>
        <button (click)="toggle()">Toggle</button>
    `,
})
export class ExampleComponent {
    isActive = true;

    toggle() {
        this.isActive = !this.isActive;
    }
}
            

329. How do you use Angular's `ngModel` for two-way data binding?

The `ngModel` directive is used for two-way data binding between the form control and the component.


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

@Component({
    selector: 'app-two-way-binding',
    template: `
        <input [(ngModel)]="value" />
        <p>{{ value }}</p>
    `,
})
export class TwoWayBindingComponent {
    value = 'Initial value';
}
            

330. How do you use Angular's `@Injectable` decorator for services?

The `@Injectable` decorator marks a class as a service that can be injected into other components or services.


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

@Injectable({
    providedIn: 'root'
})
export class ExampleService {
    getData() {
        return ['Data 1', 'Data 2'];
    }
}
            

331. How do you use Angular's `Router` service for navigation?

The `Router` service is used to programmatically navigate between routes.


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

@Component({
    selector: 'app-navigate',
    template: `
        <button (click)="goToHome()">Go to Home</button>
    `,
})
export class NavigateComponent {
    constructor(private router: Router) { }

    goToHome() {
        this.router.navigate(['/home']);
    }
}
            

332. How do you implement Angular's route resolvers?

Route resolvers are used to fetch data before navigating to a route.


import { Injectable } from '@angular/core';
import { Resolve, RouterStateSnapshot, ActivatedRouteSnapshot } from '@angular/router';
import { Observable } from 'rxjs';
import { ApiService } from './api.service';

@Injectable({
    providedIn: 'root'
})
export class DataResolver implements Resolve<any> {
    constructor(private apiService: ApiService) { }

    resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> {
        return this.apiService.getData();
    }
}
            

333. How do you create Angular form controls dynamically?

Dynamic form controls can be created using Angular's `FormBuilder` service.


import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
    selector: 'app-dynamic-form',
    template: `
        <form [formGroup]="formGroup">
            <input formControlName="dynamicControl" />
        </form>
    `,
})
export class DynamicFormComponent {
    formGroup: FormGroup;

    constructor(private fb: FormBuilder) {
        this.formGroup = this.fb.group({
            dynamicControl: ['']
        });
    }
}
            

334. How do you implement Angular's `ngFor` directive with trackBy?

The `trackBy` function improves performance by tracking items by their identity.


@Component({
    selector: 'app-list',
    template: `
        <ul>
            <li *ngFor="let item of items; trackBy: trackByFn">{{ item.name }}</li>
        </ul>
    `,
})
export class ListComponent {
    items = [{ id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }];

    trackByFn(index: number, item: any) {
        return item.id;
    }
}
            

335. How do you implement Angular's `ngIf` directive with `else`?

The `ngIf` directive can conditionally display elements with an `else` block.


@Component({
    selector: 'app-condition',
    template: `
        <div *ngIf="isVisible; else elseBlock">Visible</div>
        <ng-template #elseBlock>Not visible</ng-template>
    `,
})
export class ConditionComponent {
    isVisible = true;
}
            

336. How do you use Angular's `HttpClient` for POST requests?

`HttpClient` is used for making POST requests to a backend API.


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

@Injectable({
    providedIn: 'root'
})
export class ApiService {
    constructor(private http: HttpClient) { }

    postData(data: any) {
        return this.http.post('https://api.example.com/data', data);
    }
}
            

337. How do you implement Angular's `FormArray` for dynamic forms?

The `FormArray` is used to manage an array of form controls.


import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';

@Component({
    selector: 'app-dynamic-form-array',
    template: `
        <form [formGroup]="formGroup">
            <div formArrayName="items">
                <div *ngFor="let item of items.controls; let i = index">
                    <input [formControlName]="i" />
                </div>
            </div>
            <button (click)="addItem()">Add Item</button>
        </form>
    `,
})
export class DynamicFormArrayComponent {
    formGroup: FormGroup;

    constructor(private fb: FormBuilder) {
        this.formGroup = this.fb.group({
            items: this.fb.array([this.fb.control('')])
        });
    }

    get items() {
        return this.formGroup.get('items') as FormArray;
    }

    addItem() {
        this.items.push(this.fb.control(''));
    }
}
            

338. How do you implement Angular's `ngOnDestroy` lifecycle hook?

The `ngOnDestroy` lifecycle hook is used to clean up resources when a component is destroyed.


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

@Component({
    selector: 'app-cleanup',
    template: `<p>Cleanup example</p>`,
})
export class CleanupComponent implements OnDestroy {
    private subscription: Subscription;

    ngOnDestroy() {
        this.subscription.unsubscribe();
    }
}
            

339. How do you use Angular's `ng-template` for template rendering?

The `ng-template` directive defines a template that can be reused or rendered conditionally.


@Component({
    selector: 'app-template',
    template: `
        <ng-template #template let-data="data">
            </ng-template><ng-template #template let-data="data"><p>{{ data }}</p>
        </ng-template>
        <ng-container *ngTemplateOutlet="template; context: { data: 'Template data' }"></ng-container>
    `,
})
export class TemplateComponent { }
            

340. How do you implement Angular's `ngFor` directive with `trackBy`?

The `trackBy` function helps Angular track items in a list and improve rendering performance.


@Component({
    selector: 'app-track-by',
    template: `
        <ul>
            <li *ngFor="let item of items; trackBy: trackByFn">{{ item.name }}</li>
        </ul>
    `,
})
export class TrackByComponent {
    items = [{ id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }];

    trackByFn(index: number, item: any) {
        return item.id;
    }
}
            

Intermediate Angular Questions - Part 3

341. How do you use Angular's `@ViewChild` decorator with a static flag?

The `@ViewChild` decorator can be used with a static flag to determine when the query should be resolved.


import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { ChildComponent } from './child.component';

@Component({
    selector: 'app-parent',
    template: `<app-child></app-child>`,
})
export class ParentComponent implements AfterViewInit {
    @ViewChild(ChildComponent, { static: true }) child: ChildComponent;

    ngAfterViewInit() {
        console.log(this.child);
    }
}
            

342. How do you implement Angular's `ngFor` directive with a `let` syntax?

The `let` syntax in `ngFor` allows you to define a variable for each item in the loop.


@Component({
    selector: 'app-list',
    template: `
        <ul>
            <li *ngFor="let item of items; let i = index">
                {{ i + 1 }}: {{ item }}
            </li>
        </ul>
    `,
})
export class ListComponent {
    items = ['Item 1', 'Item 2', 'Item 3'];
}
            

343. How do you use Angular's `@Input` and `@Output` decorators in parent-child communication?

The `@Input` decorator is used to pass data from a parent component to a child component, while the `@Output` decorator is used to emit events from the child to the parent.


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

@Component({
    selector: 'app-child',
    template: `
        <button (click)="notifyParent()">Notify Parent</button>
    `,
})
export class ChildComponent {
    @Input() data: string;
    @Output() notify = new EventEmitter<string>();

    notifyParent() {
        this.notify.emit('Data from child');
    }
}

@Component({
    selector: 'app-parent',
    template: `
        <app-child [data]="parentData" (notify)="handleNotification($event)"></app-child>
    `,
})
export class ParentComponent {
    parentData = 'Data from parent';

    handleNotification(message: string) {
        console.log(message);
    }
}
            

344. How do you use Angular's `@ContentChildren` decorator?

The `@ContentChildren` decorator queries for multiple projected content elements in a component.


import { Component, ContentChildren, QueryList, AfterContentInit } from '@angular/core';
import { ChildComponent } from './child.component';

@Component({
    selector: 'app-parent',
    template: `<ng-content></ng-content>`,
})
export class ParentComponent implements AfterContentInit {
    @ContentChildren(ChildComponent) children: QueryList<ChildComponent>;

    ngAfterContentInit() {
        this.children.forEach(child => console.log(child));
    }
}
            

345. How do you use Angular's `FormGroup` and `FormControl` in reactive forms?

`FormGroup` and `FormControl` are used to create and manage reactive forms.


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

@Component({
    selector: 'app-reactive-form',
    template: `
        <form [formGroup]="formGroup" (ngSubmit)="onSubmit()">
            <input formControlName="name" />
            <button type="submit">Submit</button>
        </form>
    `,
})
export class ReactiveFormComponent {
    formGroup: FormGroup;

    constructor(private fb: FormBuilder) {
        this.formGroup = this.fb.group({
            name: ['', Validators.required]
        });
    }

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

346. How do you use Angular's `FormBuilder` service?

The `FormBuilder` service simplifies form creation and validation in Angular forms.


import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
    selector: 'app-builder-form',
    template: `
        <form [formGroup]="formGroup">
            <input formControlName="email" />
        </form>
    `,
})
export class BuilderFormComponent {
    formGroup: FormGroup;

    constructor(private fb: FormBuilder) {
        this.formGroup = this.fb.group({
            email: ['']
        });
    }
}
            

347. How do you use Angular's `Validators` class for form validation?

The `Validators` class provides built-in validation functions for forms.


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

@Component({
    selector: 'app-validate-form',
    template: `
        <form [formGroup]="formGroup" (ngSubmit)="onSubmit()">
            <input formControlName="email" />
            <div *ngIf="formGroup.controls.email.invalid">Invalid email</div>
            <button type="submit">Submit</button>
        </form>
    `,
})
export class ValidateFormComponent {
    formGroup: FormGroup;

    constructor(private fb: FormBuilder) {
        this.formGroup = this.fb.group({
            email: ['', [Validators.required, Validators.email]]
        });
    }

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

348. How do you use Angular's `Router` for lazy loading?

Lazy loading allows modules to be loaded on demand, improving application performance.


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

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

349. How do you handle form submission with Angular's `ReactiveForms`?

Form submission in reactive forms can be handled by subscribing to the form's `valueChanges` or `statusChanges` observable.


import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
    selector: 'app-reactive-form',
    template: `
        <form [formGroup]="formGroup" (ngSubmit)="onSubmit()">
            <input formControlName="name" />
            <button type="submit">Submit</button>
        </form>
    `,
})
export class ReactiveFormComponent {
    formGroup: FormGroup;

    constructor(private fb: FormBuilder) {
        this.formGroup = this.fb.group({
            name: ['']
        });

        this.formGroup.valueChanges.subscribe(value => {
            console.log('Form value changed:', value);
        });
    }

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

350. How do you use Angular's `HttpInterceptor` for global HTTP handling?

An `HttpInterceptor` can be used to modify HTTP requests or responses globally.


import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const clonedReq = req.clone({
            setHeaders: {
                Authorization: `Bearer your-token`
            }
        });

        return next.handle(clonedReq);
    }
}
            

351. How do you use Angular's `Router` for route guards?

Route guards can be used to control access to routes based on certain conditions.


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

@Injectable({
    providedIn: 'root'
})
export class AuthGuard implements CanActivate {
    constructor(private router: Router) {}

    canActivate(): boolean {
        const isLoggedIn = false; // Replace with actual login check
        if (!isLoggedIn) {
            this.router.navigate(['/login']);
            return false;
        }
        return true;
    }
}
            

352. How do you use Angular's `Directive` to create a custom directive?

Custom directives can be created to extend HTML elements with additional behavior.


import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';

@Directive({
    selector: '[appHighlight]'
})
export class HighlightDirective {
    constructor(private el: ElementRef, private renderer: Renderer2) {}

    @HostListener('mouseenter') onMouseEnter() {
        this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow');
    }

    @HostListener('mouseleave') onMouseLeave() {
        this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'transparent');
    }
}
            

353. How do you use Angular's `ChangeDetectorRef` to manually trigger change detection?

The `ChangeDetectorRef` service allows you to manually control change detection.


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

@Component({
    selector: 'app-manual-detection',
    template: `<p>{{ message }}</p>`,
})
export class ManualDetectionComponent {
    message = 'Initial message';

    constructor(private cdRef: ChangeDetectorRef) {}

    updateMessage() {
        this.message = 'Updated message';
        this.cdRef.detectChanges();
    }
}
            

354. How do you use Angular's `EventEmitter` to communicate between components?

The `EventEmitter` class is used to emit custom events from child components to parent components.


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

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

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

@Component({
    selector: 'app-parent',
    template: `
        <app-child (event)="handleEvent($event)"></app-child>
    `,
})
export class ParentComponent {
    handleEvent(message: string) {
        console.log(message);
    }
}
            

355. How do you use Angular's `NgModule` to create feature modules?

Feature modules allow you to organize application functionality into cohesive blocks.


import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FeatureComponent } from './feature.component';

@NgModule({
    declarations: [FeatureComponent],
    imports: [CommonModule],
    exports: [FeatureComponent]
})
export class FeatureModule { }
            

356. How do you use Angular's `NgZone` for managing change detection?

The `NgZone` service helps control Angular's change detection process manually.


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

@Component({
    selector: 'app-zone',
    template: `<p>{{ message }}</p>`,
})
export class ZoneComponent {
    message = 'Initial message';

    constructor(private ngZone: NgZone) {
        this.ngZone.runOutsideAngular(() => {
            setTimeout(() => {
                this.message = 'Updated message';
                this.ngZone.run(() => console.log('Change detected'));
            }, 1000);
        });
    }
}
            

357. How do you use Angular's `@HostListener` to handle DOM events?

The `@HostListener` decorator allows you to listen to DOM events directly on the host element of a directive or component.


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

@Directive({
    selector: '[appClickTracker]'
})
export class ClickTrackerDirective {
    @HostListener('click', ['$event']) onClick(event: Event) {
        console.log('Element clicked:', event);
    }
}
            

358. How do you use Angular's `@ViewChildren` decorator for querying multiple elements?

The `@ViewChildren` decorator queries for multiple elements within the view of a component.


import { Component, ViewChildren, QueryList, AfterViewInit } from '@angular/core';
import { ChildComponent } from './child.component';

@Component({
    selector: 'app-parent',
    template: `<app-child></app-child><app-child></app-child>`,
})
export class ParentComponent implements AfterViewInit {
    @ViewChildren(ChildComponent) children: QueryList<ChildComponent>;

    ngAfterViewInit() {
        this.children.forEach(child => console.log(child));
    }
}
            

359. How do you use Angular's `ngOnChanges` lifecycle hook?

The `ngOnChanges` lifecycle hook is used to respond to changes in input properties.


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

@Component({
    selector: 'app-changes',
    template: `<p>{{ inputValue }}</p>`,
})
export class ChangesComponent implements OnChanges {
    @Input() inputValue: string;

    ngOnChanges(changes: SimpleChanges) {
        console.log('Changes:', changes);
    }
}
            

360. How do you use Angular's `ngOnInit` lifecycle hook?

The `ngOnInit` lifecycle hook is used for component initialization logic.


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

@Component({
    selector: 'app-init',
    template: `<p>Component initialized</p>`,
})
export class InitComponent implements OnInit {
    ngOnInit() {
        console.log('Component initialized');
    }
}
            

Intermediate Angular Questions - Part 4

361. How do you use Angular's `ngOnDestroy` lifecycle hook?

The `ngOnDestroy` lifecycle hook is used to clean up resources and unsubscribe from observables.


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

@Component({
    selector: 'app-destroy',
    template: `<p>Component destroyed</p>`,
})
export class DestroyComponent implements OnDestroy {
    private subscription: Subscription;

    ngOnDestroy() {
        // Unsubscribe to avoid memory leaks
        if (this.subscription) {
            this.subscription.unsubscribe();
        }
    }
}
            

362. How do you use Angular's `ngModel` for two-way data binding?

The `ngModel` directive is used for two-way data binding between form controls and component properties.


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

@Component({
    selector: 'app-two-way-binding',
    template: `
        <input [(ngModel)]="value" />
        <p>Value: {{ value }}</p>
    `,
})
export class TwoWayBindingComponent {
    value: string = '';
}
            

363. How do you use Angular's `@HostBinding` decorator?

The `@HostBinding` decorator is used to bind a property of the host element to a property of the directive or component.


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

@Directive({
    selector: '[appHighlight]'
})
export class HighlightDirective {
    @HostBinding('class.highlight') isHighlighted = true;
}
            

364. How do you use Angular's `@HostListener` decorator to listen to DOM events?

The `@HostListener` decorator allows you to listen to events on the host element of the directive or component.


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

@Directive({
    selector: '[appClickTracker]'
})
export class ClickTrackerDirective {
    @HostListener('click', ['$event']) onClick(event: Event) {
        console.log('Element clicked:', event);
    }
}
            

365. How do you use Angular's `ngOnChanges` lifecycle hook?

The `ngOnChanges` lifecycle hook responds to changes in input properties.


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

@Component({
    selector: 'app-changes',
    template: `<p>{{ inputValue }}</p>`,
})
export class ChangesComponent implements OnChanges {
    @Input() inputValue: string;

    ngOnChanges(changes: SimpleChanges) {
        console.log('Changes:', changes);
    }
}
            

366. How do you use Angular's `ngOnInit` lifecycle hook?

The `ngOnInit` lifecycle hook is used for component initialization logic.


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

@Component({
    selector: 'app-init',
    template: `<p>Component initialized</p>`,
})
export class InitComponent implements OnInit {
    ngOnInit() {
        console.log('Component initialized');
    }
}
            

367. How do you use Angular's `ngAfterViewInit` lifecycle hook?

The `ngAfterViewInit` lifecycle hook is used after the component's view and child views have been initialized.


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

@Component({
    selector: 'app-view-init',
    template: `<div #myDiv>Content</div>`,
})
export class ViewInitComponent implements AfterViewInit {
    @ViewChild('myDiv') div: ElementRef;

    ngAfterViewInit() {
        console.log(this.div.nativeElement.textContent);
    }
}
            

368. How do you use Angular's `ngAfterContentInit` lifecycle hook?

The `ngAfterContentInit` lifecycle hook is used after Angular initializes the content of the component.


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

@Component({
    selector: 'app-content-init',
    template: `<ng-content></ng-content>`,
})
export class ContentInitComponent implements AfterContentInit {
    @ContentChild('content') content: ElementRef;

    ngAfterContentInit() {
        console.log(this.content.nativeElement.textContent);
    }
}
            

369. How do you use Angular's `ngAfterViewChecked` lifecycle hook?

The `ngAfterViewChecked` lifecycle hook is used after Angular checks the component's view and child views.


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

@Component({
    selector: 'app-view-checked',
    template: `<p>Check view</p>`,
})
export class ViewCheckedComponent implements AfterViewChecked {
    ngAfterViewChecked() {
        console.log('View checked');
    }
}
            

370. How do you use Angular's `ngAfterContentChecked` lifecycle hook?

The `ngAfterContentChecked` lifecycle hook is used after Angular checks the content projected into the component.


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

@Component({
    selector: 'app-content-checked',
    template: `<p>Check content</p>`,
})
export class ContentCheckedComponent implements AfterContentChecked {
    ngAfterContentChecked() {
        console.log('Content checked');
    }
}
            

371. How do you use Angular's `ngOnDestroy` lifecycle hook for cleanup?

The `ngOnDestroy` lifecycle hook is used to perform cleanup just before Angular destroys the component.


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

@Component({
    selector: 'app-destroy',
    template: `<p>Component destroyed</p>`,
})
export class DestroyComponent implements OnDestroy {
    private subscription: Subscription;

    ngOnDestroy() {
        // Unsubscribe to avoid memory leaks
        if (this.subscription) {
            this.subscription.unsubscribe();
        }
    }
}
            

372. How do you use Angular's `@Input` decorator for input binding?

The `@Input` decorator allows data to be passed from a parent component to a child component.


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

@Component({
    selector: 'app-child',
    template: `<p>{{ data }}</p>`,
})
export class ChildComponent {
    @Input() data: string;
}

@Component({
    selector: 'app-parent',
    template: `<app-child [data]="parentData"></app-child>`,
})
export class ParentComponent {
    parentData = 'Data from parent';
}
            

373. How do you use Angular's `@Output` decorator for output binding?

The `@Output` decorator is used to emit events from a child component to a parent component.


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

@Component({
    selector: 'app-child',
    template: `<button (click)="sendData()">Send Data</button>`,
})
export class ChildComponent {
    @Output() dataEvent = new EventEmitter<string>();

    sendData() {
        this.dataEvent.emit('Data from child');
    }
}

@Component({
    selector: 'app-parent',
    template: `
        <app-child (dataEvent)="receiveData($event)"></app-child>
        <p>{{ receivedData }}</p>
    `,
})
export class ParentComponent {
    receivedData: string;

    receiveData(data: string) {
        this.receivedData = data;
    }
}
            

374. How do you use Angular's `@ViewChild` decorator for querying a single element?

The `@ViewChild` decorator allows querying a single element or directive from the component's view.


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

@Component({
    selector: 'app-view-child',
    template: `<div #myDiv>Content</div>`,
})
export class ViewChildComponent implements AfterViewInit {
    @ViewChild('myDiv') div: ElementRef;

    ngAfterViewInit() {
        console.log(this.div.nativeElement.textContent);
    }
}
            

375. How do you use Angular's `NgModule` to create a shared module?

A shared module allows you to share common functionality across multiple modules.


import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SharedComponent } from './shared.component';

@NgModule({
    declarations: [SharedComponent],
    imports: [CommonModule],
    exports: [SharedComponent]
})
export class SharedModule { }
            

376. How do you use Angular's `@NgModule` to configure routes?

Routing configuration is done in the `@NgModule` decorator with the `RouterModule.forRoot` method.


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

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

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

377. How do you use Angular's `ActivatedRoute` to access route parameters?

The `ActivatedRoute` service provides access to the route parameters of the active route.


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

@Component({
    selector: 'app-route',
    template: `<p>Parameter: {{ param }}</p>`,
})
export class RouteComponent implements OnInit {
    param: string;

    constructor(private route: ActivatedRoute) {}

    ngOnInit() {
        this.route.paramMap.subscribe(params => {
            this.param = params.get('id');
        });
    }
}
            

378. How do you use Angular's `RouterLink` directive for navigation?

The `RouterLink` directive is used to bind a link to a route in the Angular router.


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

@Component({
    selector: 'app-navigation',
    template: `
        <a routerLink="/home">Home</a>
        <a routerLink="/about">About</a>
    `,
})
export class NavigationComponent { }
            

379. How do you use Angular's `Router` service for programmatic navigation?

The `Router` service allows you to navigate programmatically to different routes.


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

@Component({
    selector: 'app-navigation',
    template: `<button (click)="navigate()">Go to About</button>`,
})
export class NavigationComponent {
    constructor(private router: Router) {}

    navigate() {
        this.router.navigate(['/about']);
    }
}
            

380. How do you use Angular's `FormControl` to manage form inputs?

The `FormControl` class is used to manage the value and validation status of form inputs.


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

@Component({
    selector: 'app-form',
    template: `
        <input [formControl]="nameControl" />
        <p>Value: {{ nameControl.value }}</p>
    `,
})
export class FormComponent {
    nameControl = new FormControl('');
}
            

Intermediate Angular Questions - Part 5

381. How do you use Angular's `FormArray` to manage an array of form controls?

The `FormArray` class is used to manage an array of form controls.


import { Component } from '@angular/core';
import { FormArray, FormBuilder, FormGroup } from '@angular/forms';

@Component({
    selector: 'app-form-array',
    template: `
        <form [formGroup]="form">
            <div formArrayName="items">
                <div *ngFor="let item of items.controls; let i = index">
                    <input [formControlName]="i" />
                </div>
            </div>
            <button (click)="addItem()">Add Item</button>
        </form>
    `,
})
export class FormArrayComponent {
    form: FormGroup;

    constructor(private fb: FormBuilder) {
        this.form = this.fb.group({
            items: this.fb.array([this.fb.control('')])
        });
    }

    get items() {
        return this.form.get('items') as FormArray;
    }

    addItem() {
        this.items.push(this.fb.control(''));
    }
}
            

382. How do you use Angular's `ReactiveForms` to create a form with validation?

Reactive forms allow you to create forms with validation using `FormControl` and `FormGroup` classes.


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

@Component({
    selector: 'app-reactive-form',
    template: `
        <form [formGroup]="form" (ngSubmit)="onSubmit()">
            <input formControlName="name" placeholder="Name" />
            <div *ngIf="form.controls.name.invalid && form.controls.name.touched">
                Name is required
            </div>
            <button type="submit" [disabled]="form.invalid">Submit</button>
        </form>
    `,
})
export class ReactiveFormComponent {
    form: FormGroup;

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

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

383. How do you use Angular's `FormBuilder` to create a form with nested controls?

The `FormBuilder` class helps create complex forms with nested controls.


import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
    selector: 'app-nested-form',
    template: `
        <form [formGroup]="form">
            <div formGroupName="address">
                <input formControlName="street" placeholder="Street" />
                <input formControlName="city" placeholder="City" />
            </div>
        </form>
    `,
})
export class NestedFormComponent {
    form: FormGroup;

    constructor(private fb: FormBuilder) {
        this.form = this.fb.group({
            address: this.fb.group({
                street: [''],
                city: ['']
            })
        });
    }
}
            

384. How do you use Angular's `Validators` to add custom validation?

You can create custom validators and use them with form controls.


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

@Component({
    selector: 'app-custom-validation',
    template: `
        <form [formGroup]="form">
            <input formControlName="password" placeholder="Password" />
            <div *ngIf="form.controls.password.errors?.pattern">
                Password must contain at least one uppercase letter
            </div>
        </form>
    `,
})
export class CustomValidationComponent {
    form: FormGroup;

    constructor(private fb: FormBuilder) {
        this.form = this.fb.group({
            password: ['', [Validators.required, this.uppercaseValidator]]
        });
    }

    uppercaseValidator(control) {
        const hasUppercase = /[A-Z]/.test(control.value);
        return hasUppercase ? null : { pattern: true };
    }
}
            

385. How do you use Angular's `AsyncValidator` for asynchronous validation?

Asynchronous validators are used to perform validation that requires an HTTP request or other async operations.


import { Component } from '@angular/core';
import { FormBuilder, FormGroup, AsyncValidatorFn, AbstractControl } from '@angular/forms';
import { Observable, of } from 'rxjs';
import { debounceTime, map, catchError } from 'rxjs/operators';

@Component({
    selector: 'app-async-validator',
    template: `
        <form [formGroup]="form">
            <input formControlName="username" placeholder="Username" />
            <div *ngIf="form.controls.username.errors?.taken">
                Username is taken
            </div>
        </form>
    `,
})
export class AsyncValidatorComponent {
    form: FormGroup;

    constructor(private fb: FormBuilder) {
        this.form = this.fb.group({
            username: ['', null, this.usernameValidator()]
        });
    }

    usernameValidator(): AsyncValidatorFn {
        return (control: AbstractControl): Observable<any> => {
            return of(control.value).pipe(
                debounceTime(300),
                map(value => value === 'admin' ? { taken: true } : null),
                catchError(() => of(null))
            );
        };
    }
}
            

386. How do you use Angular's `HttpClient` to make HTTP requests?

The `HttpClient` service is used to perform HTTP requests.


import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
    selector: 'app-http',
    template: `
        <p>Data: {{ data | json }}</p>
    `,
})
export class HttpComponent implements OnInit {
    data: any;

    constructor(private http: HttpClient) {}

    ngOnInit() {
        this.http.get('https://api.example.com/data').subscribe(response => {
            this.data = response;
        });
    }
}
            

387. How do you use Angular's `HttpInterceptor` to modify HTTP requests?

The `HttpInterceptor` allows you to intercept and modify HTTP requests and responses.


import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const cloned = req.clone({
            setHeaders: {
                Authorization: 'Bearer my-token'
            }
        });
        return next.handle(cloned);
    }
}
            

388. How do you use Angular's `HttpParams` to build query parameters?

The `HttpParams` class is used to build query parameters for HTTP requests.


import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';

@Component({
    selector: 'app-http-params',
    template: `
        <p>Data: {{ data | json }}</p>
    `,
})
export class HttpParamsComponent implements OnInit {
    data: any;

    constructor(private http: HttpClient) {}

    ngOnInit() {
        const params = new HttpParams().set('param1', 'value1').set('param2', 'value2');
        this.http.get('https://api.example.com/data', { params }).subscribe(response => {
            this.data = response;
        });
    }
}
            

389. How do you use Angular's `NgModel` for two-way data binding?

The `NgModel` directive is used for two-way data binding in Angular forms.


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

@Component({
    selector: 'app-ng-model',
    template: `
        <input [(ngModel)]="name" placeholder="Name" />
        <p>Name: {{ name }}</p>
    `,
})
export class NgModelComponent {
    name: string = '';
}
            

390. How do you use Angular's `Custom Pipe` to transform data?

Custom pipes allow you to transform data before displaying it in the template.


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

@Pipe({
    name: 'reverse'
})
export class ReversePipe implements PipeTransform {
    transform(value: string): string {
        return value.split('').reverse().join('');
    }
}
            

391. How do you use Angular's `@HostListener` to listen to DOM events?

The `@HostListener` decorator allows you to listen to DOM events in your component or directive.


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

@Directive({
    selector: '[appHover]'
})
export class HoverDirective {
    @HostListener('mouseenter') onMouseEnter() {
        console.log('Mouse entered');
    }

    @HostListener('mouseleave') onMouseLeave() {
        console.log('Mouse left');
    }
}
            

392. How do you use Angular's `@ContentChild` to access projected content?

The `@ContentChild` decorator is used to access a single child element projected into a component.


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

@Component({
    selector: 'app-content-child',
    template: `<ng-content></ng-content>`,
})
export class ContentChildComponent implements AfterContentInit {
    @ContentChild('content') content: ElementRef;

    ngAfterContentInit() {
        console.log(this.content.nativeElement.textContent);
    }
}
            

393. How do you use Angular's `ChangeDetectorRef` to manually trigger change detection?

The `ChangeDetectorRef` service allows you to manually trigger change detection.


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

@Component({
    selector: 'app-detection',
    template: `
        <p>{{ message }}</p>
        <button (click)="updateMessage()">Update Message</button>
    `,
})
export class DetectionComponent {
    message: string = 'Initial Message';

    constructor(private cd: ChangeDetectorRef) {}

    updateMessage() {
        this.message = 'Updated Message';
        this.cd.detectChanges();
    }
}
            

394. How do you use Angular's `@Injectable` decorator to create a service?

The `@Injectable` decorator is used to create a service that can be injected into other components or services.


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

@Injectable({
    providedIn: 'root'
})
export class DataService {
    getData() {
        return ['Item1', 'Item2', 'Item3'];
    }
}
            

395. How do you use Angular's `@NgModule` to configure providers?

Providers can be configured in the `@NgModule` decorator to be available throughout the application or module.


import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DataService } from './data.service';

@NgModule({
    imports: [CommonModule],
    providers: [DataService]
})
export class SharedModule { }
            

396. How do you use Angular's `ng-content` to project content into a component?

The `ng-content` directive is used to project content into a component's template.


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

@Component({
    selector: 'app-content',
    template: `<ng-content></ng-content>`,
})
export class ContentComponent { }
            

397. How do you use Angular's `@Inject` decorator for dependency injection?

The `@Inject` decorator allows you to specify a dependency to be injected into a component or service.


import { Component, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';

@Component({
    selector: 'app-doc',
    template: `<p>Document title: {{ title }}</p>`,
})
export class DocComponent {
    title: string;

    constructor(@Inject(DOCUMENT) private document: Document) {
        this.title = this.document.title;
    }
}
            

398. How do you use Angular's `@HostBinding` to bind properties to a host element?

The `@HostBinding` decorator is used to bind properties to the host element of a directive or component.


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

@Directive({
    selector: '[appHighlight]'
})
export class HighlightDirective {
    @HostBinding('class.highlighted') isHighlighted = true;
}
            

399. How do you use Angular's `@Host` decorator for dependency injection?

The `@Host` decorator allows you to inject a dependency from the host element.


import { Directive, Host } from '@angular/core';
import { DataService } from './data.service';

@Directive({
    selector: '[appHost]',
})
export class HostDirective {
    constructor(@Host() private dataService: DataService) {
        console.log(this.dataService.getData());
    }
}
            

400. How do you use Angular's `ngOnInit` lifecycle hook?

The `ngOnInit` lifecycle hook is used to perform initialization logic after Angular has initialized the component's data-bound properties.


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

@Component({
    selector: 'app-init',
    template: `<p>Component initialized</p>`,
})
export class InitComponent implements OnInit {
    ngOnInit() {
        console.log('Component initialized');
    }
}
            

 

Intermediate Angular Questions - Part 6

401. How do you use Angular's `ngOnDestroy` lifecycle hook to clean up resources?

The `ngOnDestroy` lifecycle hook is used to perform cleanup just before Angular destroys the component or directive.


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

@Component({
    selector: 'app-destroy',
    template: `<p>Component is being destroyed</p>`,
})
export class DestroyComponent implements OnDestroy {
    private subscription: Subscription = new Subscription();

    ngOnDestroy() {
        this.subscription.unsubscribe();
    }
}
            

402. How do you use Angular's `@ViewChild` to access a child component or element?

The `@ViewChild` decorator allows you to access a child component or element within the parent component.


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

@Component({
    selector: 'app-view-child',
    template: `<p #paragraph>Some text</p>`,
})
export class ViewChildComponent implements AfterViewInit {
    @ViewChild('paragraph') paragraph: ElementRef;

    ngAfterViewInit() {
        console.log(this.paragraph.nativeElement.textContent);
    }
}
            

403. How do you use Angular's `@ContentChildren` to access multiple projected content elements?

The `@ContentChildren` decorator is used to access multiple child elements projected into a component.


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

@Component({
    selector: 'app-content-children',
    template: `<ng-content></ng-content>`,
})
export class ContentChildrenComponent implements AfterContentInit {
    @ContentChildren('content') contents: QueryList<ElementRef>;

    ngAfterContentInit() {
        this.contents.forEach(content => {
            console.log(content.nativeElement.textContent);
        });
    }
}
            

404. How do you use Angular's `ngOnChanges` lifecycle hook to respond to input property changes?

The `ngOnChanges` lifecycle hook allows you to respond to changes in input properties.


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

@Component({
    selector: 'app-changes',
    template: `<p>{{ value }}</p>`,
})
export class ChangesComponent implements OnChanges {
    @Input() value: string;

    ngOnChanges(changes: SimpleChanges) {
        console.log('Changes:', changes);
    }
}
            

405. How do you use Angular's `ngFor` to loop through an array in a template?

The `ngFor` directive is used to iterate over arrays or collections in Angular templates.


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

@Component({
    selector: 'app-ng-for',
    template: `
        <ul>
            <li *ngFor="let item of items">{{ item }}</li>
        </ul>
    `,
})
export class NgForComponent {
    items = ['Item 1', 'Item 2', 'Item 3'];
}
            

406. How do you use Angular's `ngIf` to conditionally display elements?

The `ngIf` directive conditionally includes or excludes elements from the DOM.


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

@Component({
    selector: 'app-ng-if',
    template: `
        <div *ngIf="isVisible">This is visible</div>
    `,
})
export class NgIfComponent {
    isVisible = true;
}
            

407. How do you use Angular's `ngClass` to apply CSS classes conditionally?

The `ngClass` directive is used to dynamically add or remove CSS classes based on expressions.


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

@Component({
    selector: 'app-ng-class',
    template: `
        <div [ngClass]="{'active': isActive, 'inactive': !isActive}">
            Conditional classes
        </div>
    `,
})
export class NgClassComponent {
    isActive = true;
}
            

408. How do you use Angular's `ngStyle` to apply inline styles conditionally?

The `ngStyle` directive allows you to apply inline styles conditionally based on expressions.


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

@Component({
    selector: 'app-ng-style',
    template: `
        <div [ngStyle]="{'color': color, 'font-size': fontSize}">
            Styled text
        </div>
    `,
})
export class NgStyleComponent {
    color = 'blue';
    fontSize = '20px';
}
            

409. How do you use Angular's `@Pipe` to create a custom pipe?

The `@Pipe` decorator is used to create custom pipes to transform data in templates.


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

@Pipe({
    name: 'uppercase'
})
export class UppercasePipe implements PipeTransform {
    transform(value: string): string {
        return value.toUpperCase();
    }
}
            

410. How do you use Angular's `ngModel` with two-way data binding in a form?

The `ngModel` directive is used for two-way data binding in Angular forms.


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

@Component({
    selector: 'app-ng-model',
    template: `
        <input [(ngModel)]="name" placeholder="Name" />
        <p>Name: {{ name }}</p>
    `,
})
export class NgModelComponent {
    name: string = '';
}
            

411. How do you use Angular's `ReactiveForms` to handle form submissions?

Reactive forms provide a way to handle form submissions with more control over validation and state.


import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
    selector: 'app-reactive-form',
    template: `
        <form [formGroup]="form" (ngSubmit)="onSubmit()">
            <input formControlName="name" placeholder="Name" />
            <button type="submit">Submit</button>
        </form>
    `,
})
export class ReactiveFormComponent {
    form: FormGroup;

    constructor(private fb: FormBuilder) {
        this.form = this.fb.group({
            name: ['']
        });
    }

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

412. How do you use Angular's `FormBuilder` to create a form group?

The `FormBuilder` service is used to create form groups in a reactive form.


import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
    selector: 'app-form-builder',
    template: `
        <form [formGroup]="form">
            <input formControlName="email" placeholder="Email" />
        </form>
    `,
})
export class FormBuilderComponent {
    form: FormGroup;

    constructor(private fb: FormBuilder) {
        this.form = this.fb.group({
            email: ['']
        });
    }
}
            

413. How do you use Angular's `HttpInterceptor` to intercept HTTP requests?

The `HttpInterceptor` interface allows you to intercept and modify HTTP requests and responses.


import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const authReq = req.clone({
            headers: req.headers.set('Authorization', 'Bearer my-token')
        });
        return next.handle(authReq);
    }
}
            

414. How do you use Angular's `HttpClient` to handle errors in HTTP requests?

The `HttpClient` service provides methods to handle errors using RxJS operators.


import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs';

@Component({
    selector: 'app-http-error',
    template: `<p>Check console for errors</p>`,
})
export class HttpErrorComponent {
    constructor(private http: HttpClient) {
        this.http.get('https://api.example.com/data')
            .pipe(catchError(error => {
                console.error('Error occurred:', error);
                return of([]);
            }))
            .subscribe(response => {
                console.log(response);
            });
    }
}
            

415. How do you use Angular's `@Directive` to create a custom directive?

The `@Directive` decorator is used to create custom directives that can manipulate the DOM.


import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';

@Directive({
    selector: '[appHighlight]'
})
export class HighlightDirective {
    constructor(private el: ElementRef, private renderer: Renderer2) {}

    @HostListener('mouseenter') onMouseEnter() {
        this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow');
    }

    @HostListener('mouseleave') onMouseLeave() {
        this.renderer.removeStyle(this.el.nativeElement, 'backgroundColor');
    }
}
            

416. How do you use Angular's `Renderer2` to interact with the DOM?

The `Renderer2` service allows you to interact with the DOM in a safe way.


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

@Directive({
    selector: '[appColor]'
})
export class ColorDirective {
    constructor(private el: ElementRef, private renderer: Renderer2) {
        this.renderer.setStyle(this.el.nativeElement, 'color', 'blue');
    }
}
            

417. How do you use Angular's `@ViewChildren` to query multiple elements or components?

The `@ViewChildren` decorator allows you to query and access multiple child elements or components.


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

@Component({
    selector: 'app-view-children',
    template: `<div #item *ngFor="let i of items">{{ i }}</div>`,
})
export class ViewChildrenComponent implements AfterViewInit {
    @ViewChildren('item') items: QueryList<ElementRef>;

    ngAfterViewInit() {
        this.items.forEach(item => {
            console.log(item.nativeElement.textContent);
        });
    }
}
            

418. How do you use Angular's `@NgModule` to create feature modules?

Feature modules are created using the `@NgModule` decorator to group related components, directives, and services.


import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FeatureComponent } from './feature.component';

@NgModule({
    imports: [CommonModule],
    declarations: [FeatureComponent],
    exports: [FeatureComponent]
})
export class FeatureModule { }
            

419. How do you use Angular's `RouterModule` to configure routes?

The `RouterModule` is used to configure routes and navigation in an Angular application.


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

const routes: Routes = [
    { path: 'home', component: HomeComponent },
    { path: 'about', component: AboutComponent },
    { path: '', redirectTo: '/home', pathMatch: 'full' }
];

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

420. How do you use Angular's `ActivatedRoute` to get route parameters?

The `ActivatedRoute` service allows you to access route parameters in your component.


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

@Component({
    selector: 'app-route-params',
    template: `<p>Route ID: {{ id }}</p>`,
})
export class RouteParamsComponent implements OnInit {
    id: string;

    constructor(private route: ActivatedRoute) {}

    ngOnInit() {
        this.route.paramMap.subscribe(params => {
            this.id = params.get('id');
        });
    }
}
            

 

Intermediate Angular Questions - Part 7

421. How do you use Angular's `HttpClient` to send a POST request with JSON data?

The `HttpClient` service can send POST requests with JSON data using the `post` method.


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

@Component({
    selector: 'app-post-request',
    template: `<p>Check console for response</p>`,
})
export class PostRequestComponent {
    constructor(private http: HttpClient) {
        this.http.post('https://api.example.com/data', { key: 'value' })
            .subscribe(response => {
                console.log(response);
            });
    }
}
            

422. How do you use Angular's `FormArray` to manage an array of form controls?

The `FormArray` class allows you to manage an array of form controls in a reactive form.


import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';

@Component({
    selector: 'app-form-array',
    template: `
        <form [formGroup]="form">
            <div formArrayName="items">
                <div *ngFor="let item of items.controls; let i = index">
                    <input [formControlName]="i" />
                </div>
            </div>
        </form>
    `,
})
export class FormArrayComponent {
    form: FormGroup;

    get items() {
        return this.form.get('items') as FormArray;
    }

    constructor(private fb: FormBuilder) {
        this.form = this.fb.group({
            items: this.fb.array(['', '', ''])
        });
    }
}
            

423. How do you use Angular's `HttpParams` to add query parameters to an HTTP request?

The `HttpParams` class is used to construct query parameters for an HTTP request.


import { Component } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';

@Component({
    selector: 'app-http-params',
    template: `<p>Check console for response</p>`,
})
export class HttpParamsComponent {
    constructor(private http: HttpClient) {
        const params = new HttpParams().set('param1', 'value1').set('param2', 'value2');
        this.http.get('https://api.example.com/data', { params })
            .subscribe(response => {
                console.log(response);
            });
    }
}
            

424. How do you use Angular's `@HostBinding` to bind properties of the host element?

The `@HostBinding` decorator allows you to bind properties of the host element in a directive or component.


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

@Directive({
    selector: '[appHighlight]'
})
export class HighlightDirective {
    @HostBinding('class.highlighted') isHighlighted = true;
}
            

425. How do you use Angular's `@HostListener` to listen to events on the host element?

The `@HostListener` decorator allows you to listen to events on the host element in a directive or component.


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

@Directive({
    selector: '[appHover]'
})
export class HoverDirective {
    @HostListener('mouseenter') onMouseEnter() {
        console.log('Mouse entered');
    }

    @HostListener('mouseleave') onMouseLeave() {
        console.log('Mouse left');
    }
}
            

426. How do you use Angular's `@Inject` to inject dependencies into a service?

The `@Inject` decorator is used to specify a dependency to be injected into a service or component.


import { Injectable, Inject } from '@angular/core';
import { MyService } from './my-service.service';

@Injectable({
    providedIn: 'root'
})
export class MyComponentService {
    constructor(@Inject(MyService) private myService: MyService) {}
}
            

427. How do you use Angular's `@Optional` to make dependency injection optional?

The `@Optional` decorator allows you to specify that a dependency is optional.


import { Injectable, Optional } from '@angular/core';
import { OptionalService } from './optional.service';

@Injectable({
    providedIn: 'root'
})
export class MyService {
    constructor(@Optional() private optionalService?: OptionalService) {}
}
            

428. How do you use Angular's `@Self` to specify that a dependency should be resolved from the same injector?

The `@Self` decorator ensures that a dependency is resolved from the same injector, not from parent injectors.


import { Injectable, Self } from '@angular/core';
import { MyService } from './my-service.service';

@Injectable({
    providedIn: 'root'
})
export class AnotherService {
    constructor(@Self() private myService: MyService) {}
}
            

429. How do you use Angular's `@Attribute` to access the value of an attribute on the host element?

The `@Attribute` decorator allows you to access the value of an attribute on the host element.


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

@Directive({
    selector: '[appAttribute]'
})
export class AttributeDirective {
    constructor(@Attribute('data-attribute') private dataAttribute: string) {
        console.log(dataAttribute);
    }
}
            

430. How do you use Angular's `NgModule` to declare and import modules?

The `@NgModule` decorator is used to declare and import modules in an Angular application.


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

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

431. How do you use Angular's `@NgModule` to provide services at the module level?

The `providers` array in `@NgModule` allows you to specify services to be available at the module level.


import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { MyService } from './my-service.service';

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

432. How do you use Angular's `@Pipe` to create a custom pipe?

The `@Pipe` decorator is used to create custom pipes that can transform data in templates.


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

@Pipe({
    name: 'reverse'
})
export class ReversePipe implements PipeTransform {
    transform(value: string): string {
        return value.split('').reverse().join('');
    }
}
            

433. How do you use Angular's `@Injectable` to create a service?

The `@Injectable` decorator is used to define a service that can be injected into other components or services.


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

@Injectable({
    providedIn: 'root'
})
export class MyService {
    constructor() {}
}
            

434. How do you use Angular's `@Component` to create a reusable component?

The `@Component` decorator is used to define a reusable component in Angular.


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

@Component({
    selector: 'app-reusable',
    template: `<p>This is a reusable component</p>`,
})
export class ReusableComponent {}
            

435. How do you use Angular's `@ViewChild` to access a child component?

The `@ViewChild` decorator allows you to access and manipulate a child component or DOM element.


import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { ChildComponent } from './child.component';

@Component({
    selector: 'app-parent',
    template: `<app-child></app-child>`,
})
export class ParentComponent implements AfterViewInit {
    @ViewChild(ChildComponent) child: ChildComponent;

    ngAfterViewInit() {
        console.log(this.child);
    }
}
            

436. How do you use Angular's `@ContentChild` to access content projected into a component?

The `@ContentChild` decorator allows you to access and manipulate content projected into a component.


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

@Component({
    selector: 'app-content',
    template: `<ng-content></ng-content>`,
})
export class ContentComponent implements AfterContentInit {
    @ContentChild('content') content: ElementRef;

    ngAfterContentInit() {
        console.log(this.content.nativeElement.textContent);
    }
}
            

437. How do you use Angular's `@NgModule` to export components from a module?

The `exports` array in `@NgModule` allows you to specify which components, directives, and pipes should be available to other modules.


import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SharedComponent } from './shared.component';

@NgModule({
    imports: [CommonModule],
    declarations: [SharedComponent],
    exports: [SharedComponent]
})
export class SharedModule { }
            

438. How do you use Angular's `@Inject` to provide a specific token value?

The `@Inject` decorator allows you to provide a specific token value for dependency injection.


import { Injectable, Inject, InjectionToken } from '@angular/core';

export const API_URL = new InjectionToken<string>('apiUrl');

@Injectable({
    providedIn: 'root'
})
export class ApiService {
    constructor(@Inject(API_URL) private apiUrl: string) {
        console.log(apiUrl);
    }
}
            

439. How do you use Angular's `@Directive` to create a structural directive?

The `@Directive` decorator is used to create a structural directive that can change the layout of the DOM.


import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';

@Directive({
    selector: '[appIf]'
})
export class IfDirective {
    constructor(private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) {}

    @Input() set appIf(condition: boolean) {
        if (condition) {
            this.viewContainer.createEmbeddedView(this.templateRef);
        } else {
            this.viewContainer.clear();
        }
    }
}
            

440. How do you use Angular's `@NgModule` to configure providers with `forRoot` and `forChild`?

The `forRoot` and `forChild` methods are used to configure providers for root and feature modules, respectively.


import { NgModule, ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MyService } from './my-service.service';

@NgModule({
    imports: [CommonModule],
    declarations: [],
    exports: []
})
export class FeatureModule {
    static forRoot(): ModuleWithProviders<FeatureModule> {
        return {
            ngModule: FeatureModule,
            providers: [MyService]
        };
    }
}
            

 

Intermediate Angular Questions - Part 8

441. How do you use Angular's `BehaviorSubject` for state management?

The `BehaviorSubject` is used to manage state in Angular. It holds the current value and emits it to new subscribers.


import { BehaviorSubject } from 'rxjs';

export class StateService {
    private stateSubject = new BehaviorSubject<number>(0);
    state$ = this.stateSubject.asObservable();

    updateState(value: number) {
        this.stateSubject.next(value);
    }
}
            

442. How do you implement Angular's `OnPush` change detection strategy?

The `OnPush` strategy improves performance by only checking for changes when the input properties change or when an event occurs.


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

@Component({
    selector: 'app-onpush',
    template: `<p>OnPush change detection</p>`,
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class OnPushComponent {}
            

443. How do you use Angular's `@ViewEncapsulation` to control CSS encapsulation?

The `@ViewEncapsulation` decorator is used to control how styles are applied to components.


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

@Component({
    selector: 'app-encapsulation',
    template: `<p>ViewEncapsulation example</p>`,
    styles: [`p { color: red; }`],
    encapsulation: ViewEncapsulation.None
})
export class EncapsulationComponent {}
            

444. How do you use Angular's `Route` with route guards?

Route guards control access to routes based on conditions.


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

@Injectable({
    providedIn: 'root'
})
export class AuthGuard implements CanActivate {
    constructor(private router: Router) {}

    canActivate(): boolean {
        const isAuthenticated = false; // Replace with real authentication logic
        if (isAuthenticated) {
            return true;
        } else {
            this.router.navigate(['/login']);
            return false;
        }
    }
}
            

445. How do you create a custom Angular pipe that accepts arguments?

Custom pipes can transform data based on provided arguments.


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

@Pipe({
    name: 'multiply'
})
export class MultiplyPipe implements PipeTransform {
    transform(value: number, multiplier: number): number {
        return value * multiplier;
    }
}
            

446. How do you use Angular's `FormBuilder` to create nested form groups?

The `FormBuilder` service can be used to create complex forms with nested form groups.


import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
    selector: 'app-nested-form',
    template: `
        <form [formGroup]="form">
            <div formGroupName="personalInfo">
                <input formControlName="name" placeholder="Name">
                <input formControlName="age" placeholder="Age">
            </div>
            <div formGroupName="address">
                <input formControlName="street" placeholder="Street">
                <input formControlName="city" placeholder="City">
            </div>
        </form>
    `,
})
export class NestedFormComponent {
    form: FormGroup;

    constructor(private fb: FormBuilder) {
        this.form = this.fb.group({
            personalInfo: this.fb.group({
                name: [''],
                age: ['']
            }),
            address: this.fb.group({
                street: [''],
                city: ['']
            })
        });
    }
}
            

447. How do you use Angular's `@NgModule` to configure lazy-loaded modules?

Lazy-loaded modules can be configured in the `@NgModule` using the `loadChildren` property in routes.


import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

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

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

448. How do you use Angular's `@NgModule` to provide a singleton service?

Providing a service in the `@NgModule` ensures that it is a singleton across the entire application.


import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { MyService } from './my-service.service';

@NgModule({
    declarations: [AppComponent],
    imports: [],
    providers: [MyService], // Singleton service
    bootstrap: [AppComponent]
})
export class AppModule { }
            

449. How do you use Angular's `HttpInterceptor` to modify HTTP requests and responses?

The `HttpInterceptor` allows you to intercept and modify HTTP requests and responses.


import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const clonedRequest = req.clone({
            headers: req.headers.set('Authorization', 'Bearer token')
        });
        return next.handle(clonedRequest);
    }
}
            

450. How do you use Angular's `ChangeDetectorRef` to manually trigger change detection?

The `ChangeDetectorRef` service allows you to manually trigger change detection in your components.


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

@Component({
    selector: 'app-manual-detect',
    template: `<p>Manual change detection</p>`,
})
export class ManualDetectComponent {
    constructor(private cdr: ChangeDetectorRef) {}

    triggerChangeDetection() {
        this.cdr.detectChanges();
    }
}
            

451. How do you use Angular's `Renderer2` to manipulate the DOM?

The `Renderer2` service provides methods to manipulate the DOM in a platform-independent way.


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

@Directive({
    selector: '[appHighlight]'
})
export class HighlightDirective {
    constructor(private renderer: Renderer2, private el: ElementRef) {
        this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow');
    }
}
            

452. How do you use Angular's `NgFor` to iterate over an array of objects?

The `NgFor` directive is used to loop through an array of objects in the template.


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

@Component({
    selector: 'app-item-list',
    template: `
        <ul>
            <li *ngFor="let item of items">{{ item.name }}</li>
        </ul>
    `,
})
export class ItemListComponent {
    items = [{ name: 'Item 1' }, { name: 'Item 2' }, { name: 'Item 3' }];
}
            

453. How do you use Angular's `NgIf` to conditionally render elements?

The `NgIf` directive allows you to conditionally include or exclude elements from the DOM.


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

@Component({
    selector: 'app-conditional',
    template: `
        <p *ngIf="isVisible">This element is conditionally rendered</p>
    `,
})
export class ConditionalComponent {
    isVisible = true;
}
            

454. How do you use Angular's `FormArray` to handle dynamic form controls?

The `FormArray` allows you to manage a dynamic list of form controls.


import { Component } from '@angular/core';
import { FormBuilder, FormArray, FormGroup } from '@angular/forms';

@Component({
    selector: 'app-dynamic-form',
    template: `
        <form [formGroup]="form">
            <div formArrayName="items">
                <div *ngFor="let item of items.controls; let i = index">
                    <input [formControlName]="i" placeholder="Item {{i + 1}}">
                </div>
            </div>
            <button (click)="addItem()">Add Item</button>
        </form>
    `,
})
export class DynamicFormComponent {
    form: FormGroup;

    constructor(private fb: FormBuilder) {
        this.form = this.fb.group({
            items: this.fb.array([])
        });
    }

    get items() {
        return this.form.get('items') as FormArray;
    }

    addItem() {
        this.items.push(this.fb.control(''));
    }
}
            

455. How do you use Angular's `@HostListener` to handle DOM events?

The `@HostListener` decorator allows you to listen to DOM events directly in your component.


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

@Component({
    selector: 'app-host-listener',
    template: `<p>HostListener example</p>`,
})
export class HostListenerComponent {
    @HostListener('click', ['$event'])
    onClick(event: Event) {
        console.log('Element clicked!', event);
    }
}
            

456. How do you use Angular's `ngOnChanges` to respond to input property changes?

The `ngOnChanges` lifecycle hook is used to respond to changes in input properties.


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

@Component({
    selector: 'app-changes',
    template: `<p>ngOnChanges example</p>`,
})
export class ChangesComponent implements OnChanges {
    @Input() data: string;

    ngOnChanges(changes: SimpleChanges) {
        console.log('Changes detected:', changes);
    }
}
            

457. How do you use Angular's `ngOnInit` to initialize component data?

The `ngOnInit` lifecycle hook is used to perform initialization tasks for the component.


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

@Component({
    selector: 'app-init',
    template: `<p>ngOnInit example</p>`,
})
export class InitComponent implements OnInit {
    data: string;

    ngOnInit() {
        this.data = 'Initialized data';
    }
}
            

458. How do you use Angular's `ngOnDestroy` to clean up resources?

The `ngOnDestroy` lifecycle hook is used to perform cleanup tasks before the component is destroyed.


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

@Component({
    selector: 'app-destroy',
    template: `<p>ngOnDestroy example</p>`,
})
export class DestroyComponent implements OnDestroy {
    private subscription: Subscription;

    ngOnDestroy() {
        if (this.subscription) {
            this.subscription.unsubscribe();
        }
    }
}
            

459. How do you use Angular's `@Input` and `@Output` to communicate between parent and child components?

The `@Input` decorator allows a child component to receive data from a parent, while `@Output` allows the child to emit events to the parent.


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

@Component({
    selector: 'app-child',
    template: `
        <button (click)="sendMessage()">Send Message</button>
    `,
})
export class ChildComponent {
    @Input() message: string;
    @Output() messageEvent = new EventEmitter<string>();

    sendMessage() {
        this.messageEvent.emit('Message from child');
    }
}

@Component({
    selector: 'app-parent',
    template: `
        <app-child [message]="parentMessage" (messageEvent)="receiveMessage($event)"></app-child>
        <p>Received Message: {{ receivedMessage }}</p>
    `,
})
export class ParentComponent {
    parentMessage = 'Message from parent';
    receivedMessage: string;

    receiveMessage(message: string) {
        this.receivedMessage = message;
    }
}
            

460. How do you use Angular's `ngSwitch` to conditionally display elements based on a value?

The `ngSwitch` directive allows you to conditionally display elements based on a value.


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

@Component({
    selector: 'app-switch',
    template: `
        <div [ngSwitch]="value">
            <p *ngSwitchCase="'A'">Value is A</p>
            <p *ngSwitchCase="'B'">Value is B</p>
            <p *ngSwitchDefault>Default value</p>
        </div>
    `,
})
export class SwitchComponent {
    value = 'A';
}
            

 

Intermediate Angular Questions - Part 9

461. How do you use Angular's `@Injectable` decorator to provide a service at a specific level?

The `@Injectable` decorator is used to mark a class as a service that can be injected. You can specify the provider in `@NgModule` or directly in the component.


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

@Injectable({
    providedIn: 'root' // Singleton service provided at the root level
})
export class MyService {}
            

462. How do you use Angular's `@ContentChild` to access a child component projected into a content slot?

The `@ContentChild` decorator is used to access a child component or directive that is projected into a content slot.


import { Component, ContentChild, AfterContentInit } from '@angular/core';
import { ChildComponent } from './child.component';

@Component({
    selector: 'app-parent',
    template: `<ng-content></ng-content>`
})
export class ParentComponent implements AfterContentInit {
    @ContentChild(ChildComponent) child: ChildComponent;

    ngAfterContentInit() {
        console.log(this.child);
    }
}
            

463. How do you use Angular's `@ViewChild` to access a child component within the view?

The `@ViewChild` decorator is used to access a child component or directive within the view.


import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { ChildComponent } from './child.component';

@Component({
    selector: 'app-parent',
    template: `<app-child></app-child>`
})
export class ParentComponent implements AfterViewInit {
    @ViewChild(ChildComponent) child: ChildComponent;

    ngAfterViewInit() {
        console.log(this.child);
    }
}
            

464. How do you use Angular's `ngModel` to bind form controls to component properties?

The `ngModel` directive is used for two-way data binding with form controls.


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

@Component({
    selector: 'app-model',
    template: `<input [(ngModel)]="value" placeholder="Enter value"> <p>{{ value }}</p>`
})
export class ModelComponent {
    value: string = '';
}
            

465. How do you use Angular's `AsyncPipe` to handle asynchronous data?

The `AsyncPipe` subscribes to an observable or promise and returns the latest value it has emitted.


import { Component } from '@angular/core';
import { Observable, of } from 'rxjs';

@Component({
    selector: 'app-async',
    template: `<p>{{ data$ | async }}</p>`
})
export class AsyncComponent {
    data$: Observable<string> = of('Hello World');
}
            

466. How do you use Angular's `ngClass` to apply dynamic CSS classes?

The `ngClass` directive allows you to dynamically add or remove CSS classes based on component state.


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

@Component({
    selector: 'app-class',
    template: `<div [ngClass]="{'active': isActive, 'inactive': !isActive}">Dynamic Class</div>`
})
export class ClassComponent {
    isActive = true;
}
            

467. How do you use Angular's `ngStyle` to apply dynamic inline styles?

The `ngStyle` directive allows you to dynamically set inline styles on an element.


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

@Component({
    selector: 'app-style',
    template: `<div [ngStyle]="{ 'color': color, 'font-size': fontSize }">Styled Text</div>`
})
export class StyleComponent {
    color = 'blue';
    fontSize = '20px';
}
            

468. How do you use Angular's `ngFor` with a trackBy function to optimize rendering?

The `trackBy` function helps Angular optimize rendering by tracking items in a list.


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

@Component({
    selector: 'app-trackby',
    template: `
        <ul>
            <li *ngFor="let item of items; trackBy: trackByFn">{{ item.name }}</li>
        </ul>
    `
})
export class TrackByComponent {
    items = [{ id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }];

    trackByFn(index: number, item: any) {
        return item.id;
    }
}
            

469. How do you use Angular's `ngIf` with `else` to conditionally render elements?

The `ngIf` directive can be used with `else` to display alternate content based on a condition.


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

@Component({
    selector: 'app-if-else',
    template: `
        <div *ngIf="isVisible; else notVisible">Visible Content</div>
        <ng-template #notVisible>Not Visible Content</ng-template>
    `
})
export class IfElseComponent {
    isVisible = true;
}
            

470. How do you use Angular's `@HostBinding` to bind properties to the host element?

The `@HostBinding` decorator allows you to bind properties to the host element of the directive or component.


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

@Directive({
    selector: '[appHighlight]'
})
export class HighlightDirective {
    @HostBinding('class.highlight') isHighlighted = true;
}
            

471. How do you use Angular's `@HostListener` to listen to events on the host element?

The `@HostListener` decorator allows you to listen to events on the host element of the directive or component.


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

@Directive({
    selector: '[appClickTracker]'
})
export class ClickTrackerDirective {
    @HostListener('click', ['$event'])
    onClick(event: Event) {
        console.log('Host element clicked!', event);
    }
}
            

472. How do you use Angular's `HttpClient` to make HTTP requests?

The `HttpClient` service is used to make HTTP requests and handle responses.


import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';
import { Observable } from 'rxjs';

@Component({
    selector: 'app-http',
    template: `<p>Data: {{ data$ | async }}</p>`
})
export class HttpComponent {
    data$: Observable<any>;

    constructor(private http: HttpClient) {
        this.data$ = this.http.get('https://api.example.com/data');
    }
}
            

473. How do you use Angular's `HttpInterceptor` to modify HTTP requests and responses?

The `HttpInterceptor` allows you to intercept and modify HTTP requests and responses.


import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const clonedRequest = req.clone({
            setHeaders: { Authorization: 'Bearer token' }
        });
        return next.handle(clonedRequest);
    }
}
            

474. How do you use Angular's `Router` to navigate between routes programmatically?

The `Router` service is used to navigate between routes programmatically.


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

@Component({
    selector: 'app-navigate',
    template: `<button (click)="goToPage()">Go to Page</button>`
})
export class NavigateComponent {
    constructor(private router: Router) {}

    goToPage() {
        this.router.navigate(['/page']);
    }
}
            

475. How do you use Angular's `ActivatedRoute` to access route parameters?

The `ActivatedRoute` service allows you to access route parameters and query parameters.


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

@Component({
    selector: 'app-route',
    template: `<p>Param: {{ param }}</p>`
})
export class RouteComponent implements OnInit {
    param: string;

    constructor(private route: ActivatedRoute) {}

    ngOnInit() {
        this.route.params.subscribe(params => {
            this.param = params['id'];
        });
    }
}
            

476. How do you use Angular's `Route Guards` to protect routes?

Route guards are used to protect routes based on certain conditions.


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

@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
    constructor(private router: Router) {}

    canActivate(): boolean {
        const isAuthenticated = false; // Check authentication
        if (!isAuthenticated) {
            this.router.navigate(['/login']);
            return false;
        }
        return true;
    }
}
            

477. How do you use Angular's `RouterOutlet` to display routed components?

The `RouterOutlet` directive is used to display routed components based on the active route.


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

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

@NgModule({

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

@Component({
    selector: 'app-root',
    template: `<router-outlet></router-outlet>`
})
export class AppComponent {}
            

478. How do you use Angular's `Dependency Injection` to inject services into components?

Dependency Injection is used to inject services into components or other services.


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

@Injectable({
    providedIn: 'root'
})
export class MyService {}

import { Component } from '@angular/core';
import { MyService } from './my.service';

@Component({
    selector: 'app-example',
    template: `<p>Service injected</p>`
})
export class ExampleComponent {
    constructor(private myService: MyService) {}
}
            

479. How do you use Angular's `Custom Pipes` to transform data?

Custom pipes are used to transform data before displaying it in the template.


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

@Pipe({
    name: 'reverse'
})
export class ReversePipe implements PipeTransform {
    transform(value: string): string {
        return value.split('').reverse().join('');
    }
}

@Component({
    selector: 'app-pipe',
    template: `<p>{{ 'Angular' | reverse }}</p>`
})
export class PipeComponent {}
            

480. How do you use Angular's `ChangeDetectionStrategy` to optimize change detection?

The `ChangeDetectionStrategy` is used to control how Angular checks for changes in a component.


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

@Component({
    selector: 'app-detection',
    template: `<p>Change Detection Strategy</p>`,
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class DetectionComponent {}
            

Intermediate Angular Questions - Part 10

481. How do you use Angular's `@Inject` to inject dependencies?

The `@Inject` decorator is used to specify a provider to inject into a constructor when the dependency is not directly injectable.


import { Injectable, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';

@Injectable({
    providedIn: 'root'
})
export class DocumentService {
    constructor(@Inject(DOCUMENT) private document: Document) {}
}
            

482. How do you use Angular's `@Component` decorator to define component metadata?

The `@Component` decorator is used to define metadata for a component, such as its selector, template, and styles.


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

@Component({
    selector: 'app-example',
    templateUrl: './example.component.html',
    styleUrls: ['./example.component.css']
})
export class ExampleComponent {}
            

483. How do you use Angular's `@NgModule` to define modules?

The `@NgModule` decorator defines an Angular module by providing metadata, such as declarations, imports, and providers.


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

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

484. How do you use Angular's `ReactiveFormsModule` to build reactive forms?

The `ReactiveFormsModule` provides reactive form capabilities in Angular, allowing you to build and manage forms programmatically.


import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
    selector: 'app-reactive-form',
    template: `
        <form [formGroup]="form">
            <label for="name">Name:</label>
            <input id="name" formControlName="name">
            <button (click)="submit()">Submit</button>
        </form>
    `
})
export class ReactiveFormComponent {
    form: FormGroup;

    constructor(private fb: FormBuilder) {
        this.form = this.fb.group({
            name: ['']
        });
    }

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

485. How do you use Angular's `FormsModule` to build template-driven forms?

The `FormsModule` provides support for template-driven forms in Angular, allowing you to build forms declaratively.


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

@Component({
    selector: 'app-template-form',
    template: `
        <form #form="ngForm" (ngSubmit)="submit(form)">
            <label for="name">Name:</label>
            <input id="name" name="name" ngModel>
            <button type="submit">Submit</button>
        </form>
    `
})
export class TemplateFormComponent {
    submit(form: any) {
        console.log(form.value);
    }
}
            

486. How do you use Angular's `HttpClient` with interceptors for logging?

Interceptors can be used with `HttpClient` to log HTTP requests and responses.


import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class LoggingInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        console.log('Request made:', req);
        return next.handle(req);
    }
}
            

487. How do you use Angular's `@Output` to emit events from a child component?

The `@Output` decorator allows a child component to emit events to a parent component.


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

@Component({
    selector: 'app-child',
    template: `<button (click)="notify()">Notify</button>`
})
export class ChildComponent {
    @Output() notifyEvent = new EventEmitter<void>();

    notify() {
        this.notifyEvent.emit();
    }
}

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

@Component({
    selector: 'app-parent',
    template: `<app-child (notifyEvent)="onNotify()"></app-child>`
})
export class ParentComponent {
    onNotify() {
        console.log('Notification received!');
    }
}
            

488. How do you use Angular's `ng-template` to create reusable templates?

The `ng-template` directive allows you to define reusable templates that can be used with structural directives.


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

@Component({
    selector: 'app-template',
    template: `
        <ng-template #template let-name="name">
            </ng-template><ng-template #template let-name="name"><p>Hello, {{ name }}!</p>
        </ng-template>
        <ng-container *ngTemplateOutlet="template; context: { name: 'Angular' }"></ng-container>
    `
})
export class TemplateComponent {}
            

489. How do you use Angular's `ng-content` to project content into a component?

The `ng-content` directive is used to project content from a parent component into a child component.


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

@Component({
    selector: 'app-child',
    template: `<ng-content></ng-content>`
})
export class ChildComponent {}

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

@Component({
    selector: 'app-parent',
    template: `<app-child></app-child><app-child><p>Projected Content</p></app-child>`
})
export class ParentComponent {}
            

490. How do you use Angular's `Dynamic Component Loader` to load components dynamically?

The `ComponentFactoryResolver` allows you to dynamically create components at runtime.


import { Component, ComponentFactoryResolver, ViewChild, ViewContainerRef } from '@angular/core';
import { DynamicComponent } from './dynamic.component';

@Component({
    selector: 'app-dynamic-loader',
    template: `<ng-template #container></ng-template>`
})
export class DynamicLoaderComponent {
    @ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef;

    constructor(private resolver: ComponentFactoryResolver) {}

    loadComponent() {
        const factory = this.resolver.resolveComponentFactory(DynamicComponent);
        this.container.createComponent(factory);
    }
}
            

491. How do you use Angular's `FormArray` to manage dynamic form controls?

The `FormArray` is used to manage a collection of form controls, which can be dynamically added or removed.


import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';

@Component({
    selector: 'app-dynamic-form',
    template: `
        <form [formGroup]="form">
            <div formArrayName="items">
                <div *ngFor="let item of items.controls; let i = index">
                    <input [formControlName]="i">
                    <button (click)="removeItem(i)">Remove</button>
                </div>
            </div>
            <button (click)="addItem()">Add Item</button>
        </form>
    `
})
export class DynamicFormComponent {
    form: FormGroup;

    constructor(private fb: FormBuilder) {
        this.form = this.fb.group({
            items: this.fb.array([])
        });
    }

    get items() {
        return this.form.get('items') as FormArray;
    }

    addItem() {
        this.items.push(this.fb.control(''));
    }

    removeItem(index: number) {
        this.items.removeAt(index);
    }
}
            

492. How do you use Angular's `ChangeDetectorRef` to manually trigger change detection?

The `ChangeDetectorRef` service is used to manually trigger change detection in Angular.


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

@Component({
    selector: 'app-manual-detection',
    template: `<p>Manual Change Detection</p>`
})
export class ManualDetectionComponent {
    constructor(private cdr: ChangeDetectorRef) {}

    detectChanges() {
        this.cdr.detectChanges();
    }
}
            

493. How do you use Angular's `@HostListener` to listen to DOM events?

The `@HostListener` decorator allows you to listen to DOM events on the host element of a directive or component.


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

@Directive({
    selector: '[appClickTracker]'
})
export class ClickTrackerDirective {
    @HostListener('click', ['$event'])
    onClick(event: Event) {
        console.log('Element clicked!', event);
    }
}
            

494. How do you use Angular's `@ViewChild` to access child components or elements?

The `@ViewChild` decorator allows you to access child components, directives, or DOM elements from the parent component.


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

@Component({
    selector: 'app-parent',
    template: `<button (click)="clickChild()">Click Child</button><app-child #child></app-child>`
})
export class ParentComponent {
    @ViewChild('child') child: ElementRef;

    clickChild() {
        console.log(this.child);
    }
}
            

495. How do you use Angular's `@ContentChild` to access projected content?

The `@ContentChild` decorator allows you to access content projected into a component using `ng-content`.


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

@Component({
    selector: 'app-content',
    template: `<ng-content></ng-content>`
})
export class ContentComponent {
    @ContentChild('projectedContent') content: ElementRef;

    ngAfterContentInit() {
        console.log(this.content.nativeElement.textContent);
    }
}
            

496. How do you use Angular's `NgZone` to manage change detection?

The `NgZone` service allows you to run code inside or outside Angular's zone, which affects change detection.


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

@Component({
    selector: 'app-zone',
    template: `<p>NgZone Example</p>`
})
export class ZoneComponent {
    constructor(private ngZone: NgZone) {}

    runOutsideAngular() {
        this.ngZone.runOutsideAngular(() => {
            console.log('Running outside Angular zone');
        });
    }
}
            

497. How do you use Angular's `ViewEncapsulation` to control component styles?

The `ViewEncapsulation` enum controls how styles are applied to components.


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

@Component({
    selector: 'app-encapsulation',
    template: `<p>View Encapsulation Example</p>`,
    styles: [`p { color: blue; }`],
    encapsulation: ViewEncapsulation.Emulated
})
export class EncapsulationComponent {}
            

498. How do you use Angular's `NgModule` to configure lazy-loaded modules?

Lazy-loaded modules are configured using `NgModule` and the `RouterModule.forRoot` method with the `loadChildren` property.


import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

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

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

499. How do you use Angular's `ChangeDetectionStrategy.OnPush` to optimize performance?

The `ChangeDetectionStrategy.OnPush` strategy optimizes performance by checking for changes only when input properties change or events occur.


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

@Component({
    selector: 'app-performance',
    template: `<p>OnPush Change Detection</p>`,
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class PerformanceComponent {}
            

500. How do you use Angular's `ng-container` to conditionally render elements without adding extra DOM nodes?

The `ng-container` directive allows you to conditionally render elements without adding extra DOM nodes.


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

@Component({
    selector: 'app-container',
    template: `
        <ng-container *ngIf="isVisible">
            </ng-container><ng-container *ngIf="isVisible"><p>Conditionally Rendered Content</p>
        </ng-container>
    `
})
export class ContainerComponent {
    isVisible = true;
}
            

Intermediate Angular Questions - Part 11

501. How do you use Angular's `@Injectable` decorator to create services?

The `@Injectable` decorator marks a class as a service that can be injected into other classes.


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

@Injectable({
    providedIn: 'root'
})
export class DataService {
    getData() {
        return ['Data 1', 'Data 2', 'Data 3'];
    }
}
            

502. How do you use Angular's `ngIf` to conditionally render elements?

The `ngIf` directive conditionally includes a template based on the value of an expression.


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

@Component({
    selector: 'app-condition',
    template: `
        <div *ngIf="isVisible">This content is visible</div>
    `
})
export class ConditionComponent {
    isVisible = true;
}
            

503. How do you use Angular's `ngFor` to iterate over a list?

The `ngFor` directive is used to iterate over a list of items and render them in the template.


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

@Component({
    selector: 'app-list',
    template: `
        <ul>
            <li *ngFor="let item of items">{{ item }}</li>
        </ul>
    `
})
export class ListComponent {
    items = ['Item 1', 'Item 2', 'Item 3'];
}
            

504. How do you use Angular's `ngSwitch` to conditionally display elements?

The `ngSwitch` directive allows you to display different templates based on a value.


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

@Component({
    selector: 'app-switch',
    template: `
        <div [ngSwitch]="color">
            <div *ngSwitchCase="'red'">Red color</div>
            <div *ngSwitchCase="'blue'">Blue color</div>
            <div *ngSwitchDefault>Default color</div>
        </div>
    `
})
export class SwitchComponent {
    color = 'blue';
}
            

505. How do you use Angular's `@ViewChild` to access child elements or components?

The `@ViewChild` decorator is used to get a reference to a child component or element in the template.


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

@Component({
    selector: 'app-view-child',
    template: `<p #paragraph>Child Paragraph</p>`
})
export class ViewChildComponent {
    @ViewChild('paragraph') paragraph: ElementRef;

    ngAfterViewInit() {
        console.log(this.paragraph.nativeElement.textContent);
    }
}
            

506. How do you use Angular's `ngStyle` to apply dynamic styles?

The `ngStyle` directive allows you to apply dynamic styles to an element based on an expression.


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

@Component({
    selector: 'app-style',
    template: `
        <div [ngStyle]="{ 'color': color, 'font-size.px': fontSize }">
            Styled Text
        </div>
    `
})
export class StyleComponent {
    color = 'red';
    fontSize = 20;
}
            

507. How do you use Angular's `ngClass` to conditionally apply CSS classes?

The `ngClass` directive allows you to conditionally apply one or more CSS classes to an element.


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

@Component({
    selector: 'app-class',
    template: `
        <div [ngClass]="{ 'active': isActive, 'disabled': isDisabled }">
            Conditional Classes
        </div>
    `
})
export class ClassComponent {
    isActive = true;
    isDisabled = false;
}
            

508. How do you use Angular's `@Input` to pass data from parent to child components?

The `@Input` decorator allows a child component to receive data from its parent component.


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

@Component({
    selector: 'app-child',
    template: `<p>Received: {{ data }}</p>`
})
export class ChildComponent {
    @Input() data: string;
}

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

@Component({
    selector: 'app-parent',
    template: `<app-child [data]="parentData"></app-child>`
})
export class ParentComponent {
    parentData = 'Data from parent';
}
            

509. How do you use Angular's `@HostBinding` to bind properties to the host element?

The `@HostBinding` decorator allows you to bind properties to the host element of a directive or component.


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

@Directive({
    selector: '[appHighlight]'
})
export class HighlightDirective {
    @HostBinding('style.backgroundColor') backgroundColor = 'yellow';
}
            

510. How do you use Angular's `@HostListener` to listen to events on the host element?

The `@HostListener` decorator allows you to listen to events on the host element of a directive or component.


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

@Directive({
    selector: '[appClickTracker]'
})
export class ClickTrackerDirective {
    @HostListener('click', ['$event'])
    onClick(event: Event) {
        console.log('Element clicked:', event);
    }
}
            

511. How do you use Angular's `Router` to navigate between different routes?

The `Router` service is used to navigate between different routes in an Angular application.


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

@Component({
    selector: 'app-navigation',
    template: `<button (click)="navigate()">Go to Details</button>`
})
export class NavigationComponent {
    constructor(private router: Router) {}

    navigate() {
        this.router.navigate(['/details']);
    }
}
            

512. How do you use Angular's `ActivatedRoute` to access route parameters?

The `ActivatedRoute` service is used to access route parameters and other information about the current route.


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

@Component({
    selector: 'app-details',
    template: `<p>Item ID: {{ itemId }}</p>`
})
export class DetailsComponent implements OnInit {
    itemId: string;

    constructor(private route: ActivatedRoute) {}

    ngOnInit() {
        this.itemId = this.route.snapshot.paramMap.get('id');
    }
}
            

513. How do you use Angular's `RouterModule` to configure routes?

The `RouterModule` is used to configure application routes using the `RouterModule.forRoot` method.


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

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

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

514. How do you use Angular's `CanActivate` guard to protect routes?

The `CanActivate` guard is used to control access to routes based on conditions.


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

@Injectable({
    providedIn: 'root'
})
export class AuthGuard implements CanActivate {
    constructor(private router: Router) {}

    canActivate(): boolean {
        const isAuthenticated = false; // Example condition
        if (!isAuthenticated) {
            this.router.navigate(['/login']);
            return false;
        }
        return true;
    }
}
            

515. How do you use Angular's `HttpClient` to make HTTP requests?

The `HttpClient` service is used to make HTTP requests and handle responses.


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

@Injectable({
    providedIn: 'root'
})
export class DataService {
    constructor(private http: HttpClient) {}

    getData() {
        return this.http.get('https://api.example.com/data');
    }
}
            

516. How do you use Angular's `HttpInterceptor` to modify HTTP requests and responses?

The `HttpInterceptor` interface allows you to intercept and modify HTTP requests and responses.


import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const authReq = req.clone({ setHeaders: { Authorization: 'Bearer token' } });
        return next.handle(authReq);
    }
}
            

517. How do you use Angular's `FormBuilder` to create reactive forms?

The `FormBuilder` service simplifies the creation of reactive forms.


import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
    selector: 'app-reactive-form',
    template: `
        <form [formGroup]="form">
            <input formControlName="name">
            <input formControlName="email">
        </form>
    `
})
export class ReactiveFormComponent {
    form: FormGroup;

    constructor(private fb: FormBuilder) {
        this.form = this.fb.group({
            name: [''],
            email: ['']
        });
    }
}
            

518. How do you use Angular's `FormArray` to manage an array of form controls?

The `FormArray` allows you to manage a collection of form controls.


import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';

@Component({
    selector: 'app-dynamic-form',
    template: `
        <form [formGroup]="form">
            <div formArrayName="items">
                <div *ngFor="let item of items.controls; let i = index">
                    <input [formControlName]="i">
                    <button (click)="removeItem(i)">Remove</button>
                </div>
            </div>
            <button (click)="addItem()">Add Item</button>
        </form>
    `
})
export class DynamicFormComponent {
    form: FormGroup;

    constructor(private fb: FormBuilder) {
        this.form = this.fb.group({
            items: this.fb.array([])
        });
    }

    get items() {
        return this.form.get('items') as FormArray;
    }

    addItem() {
        this.items.push(this.fb.control(''));
    }

    removeItem(index: number) {
        this.items.removeAt(index);
    }
}
            

519. How do you use Angular's `ngOnChanges` lifecycle hook to respond to input changes?

The `ngOnChanges` lifecycle hook responds to changes in input properties.


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

@Component({
    selector: 'app-changes',
    template: `<p>Previous: {{ prevValue }}, Current: {{ currentValue }}</p>`
})
export class ChangesComponent implements OnChanges {
    @Input() value: string;
    prevValue: string;
    currentValue: string;

    ngOnChanges(changes: SimpleChanges) {
        if (changes.value) {
            this.prevValue = changes.value.previousValue;
            this.currentValue = changes.value.currentValue;
        }
    }
}
            

520. How do you use Angular's `ngAfterViewInit` lifecycle hook to perform actions after the view has been initialized?

The `ngAfterViewInit` lifecycle hook is used to perform actions after the view and child views have been initialized.


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

@Component({
    selector: 'app-after-view',
    template: `<p #paragraph>View Initialized</p>`
})
export class AfterViewComponent implements AfterViewInit {
    @ViewChild('paragraph') paragraph: ElementRef;

    ngAfterViewInit() {
        console.log(this.paragraph.nativeElement.textContent);
    }
}
            

 

Intermediate Angular Questions - Part 12

521. How do you use Angular's `ng-content` to project content into a component?

The `ng-content` directive allows you to project content into a component's view.


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

@Component({
    selector: 'app-card',
    template: `
        <div class="card">
            <ng-content></ng-content>
        </div>
    `
})
export class CardComponent {}
            

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

@Component({
    selector: 'app-root',
    template: `
        <app-card>
            </app-card><app-card><h1>Card Title</h1>
            <p>Card content goes here.</p>
        </app-card>
    `
})
export class AppComponent {}
            

522. How do you use Angular's `ng-template` to define reusable templates?

The `ng-template` directive defines reusable templates that can be instantiated later.


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

@Component({
    selector: 'app-template',
    template: `
        <ng-template #myTemplate>
            </ng-template><ng-template #myTemplate><p>This is a reusable template.</p>
        </ng-template>
        <ng-container *ngTemplateOutlet="myTemplate"></ng-container>
    `
})
export class TemplateComponent {}
            

523. How do you use Angular's `ChangeDetectionStrategy` to optimize change detection?

The `ChangeDetectionStrategy` can be set to `OnPush` to optimize change detection performance.


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

@Component({
    selector: 'app-optimized',
    template: `<p>Optimized Change Detection</p>`,
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class OptimizedComponent {}
            

524. How do you use Angular's `Renderer2` to safely manipulate DOM elements?

The `Renderer2` service is used to safely manipulate DOM elements without direct access.


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

@Component({
    selector: 'app-renderer',
    template: `<p #paragraph>Text</p>`
})
export class RendererComponent {
    constructor(private renderer: Renderer2, private el: ElementRef) {}

    ngAfterViewInit() {
        const paragraph = this.el.nativeElement.querySelector('p');
        this.renderer.setStyle(paragraph, 'color', 'blue');
    }
}
            

525. How do you use Angular's `@Directive` to create custom directives?

The `@Directive` decorator is used to create custom directives that can modify the behavior of elements.


import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';

@Directive({
    selector: '[appHighlight]'
})
export class HighlightDirective {
    constructor(private el: ElementRef, private renderer: Renderer2) {}

    @HostListener('mouseenter') onMouseEnter() {
        this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow');
    }

    @HostListener('mouseleave') onMouseLeave() {
        this.renderer.removeStyle(this.el.nativeElement, 'backgroundColor');
    }
}
            

526. How do you use Angular's `@NgModule` to define modules and their dependencies?

The `@NgModule` decorator defines a module and its components, directives, and services.


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

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

527. How do you use Angular's `Dependency Injection` to provide services?

Dependency Injection allows you to provide and inject services into components or other services.


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

@Injectable({
    providedIn: 'root'
})
export class AuthService {
    login() {
        console.log('User logged in');
    }
}

import { Component } from '@angular/core';
import { AuthService } from './auth.service';

@Component({
    selector: 'app-login',
    template: `<button (click)="login()">Login</button>`
})
export class LoginComponent {
    constructor(private authService: AuthService) {}

    login() {
        this.authService.login();
    }
}
            

528. How do you use Angular's `Observable` to handle asynchronous data streams?

The `Observable` class is used to handle asynchronous data streams and is often used with Angular's `HttpClient`.


import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Component({
    selector: 'app-data',
    template: `<p>{{ data | json }}</p>`
})
export class DataComponent implements OnInit {
    data: any;

    constructor(private http: HttpClient) {}

    ngOnInit() {
        this.getData().subscribe(response => this.data = response);
    }

    getData(): Observable<any> {
        return this.http.get('https://api.example.com/data');
    }
}
            

529. How do you use Angular's `RxJS` operators to transform data streams?

RxJS operators are used to transform and manipulate data streams.


import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';

@Component({
    selector: 'app-transformed-data',
    template: `<p>{{ data | json }}</p>`
})
export class TransformedDataComponent implements OnInit {
    data: any;

    constructor(private http: HttpClient) {}

    ngOnInit() {
        this.getData().pipe(
            map(response => response.items)
        ).subscribe(items => this.data = items);
    }

    getData() {
        return this.http.get<any>('https://api.example.com/data');
    }
}
            

530. How do you use Angular's `@Output` and `EventEmitter` to emit events from a child component?

The `@Output` decorator and `EventEmitter` are used to emit events from a child component to its parent.


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

@Component({
    selector: 'app-child',
    template: `<button (click)="notify()">Notify</button>`
})
export class ChildComponent {
    @Output() notifyEvent = new EventEmitter<string>();

    notify() {
        this.notifyEvent.emit('Event from child');
    }
}

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

@Component({
    selector: 'app-parent',
    template: `<app-child (notifyEvent)="handleNotification($event)"></app-child>`
})
export class ParentComponent {
    handleNotification(message: string) {
        console.log(message);
    }
}
            

531. How do you use Angular's `@HostBinding` to bind host element properties?

The `@HostBinding` decorator allows you to bind properties of the host element.


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

@Directive({
    selector: '[appHighlight]'
})
export class HighlightDirective {
    @HostBinding('style.backgroundColor') backgroundColor: string = 'yellow';
}
            

532. How do you use Angular's `@HostListener` to listen to events on the host element?

The `@HostListener` decorator listens to events on the host element.


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

@Directive({
    selector: '[appClickTracker]'
})
export class ClickTrackerDirective {
    @HostListener('click', ['$event'])
    onClick(event: MouseEvent) {
        console.log('Element clicked:', event);
    }
}
            

533. How do you use Angular's `ngFor` to loop through a collection of items?

The `ngFor` directive is used to loop through a collection and render each item.


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

@Component({
    selector: 'app-list',
    template: `
        <ul>
            <li *ngFor="let item of items">{{ item }}</li>
        </ul>
    `
})
export class ListComponent {
    items: string[] = ['Item 1', 'Item 2', 'Item 3'];
}
            

534. How do you use Angular's `ngIf` to conditionally include or exclude elements?

The `ngIf` directive is used to conditionally include or exclude elements based on an expression.


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

@Component({
    selector: 'app-conditional',
    template: `
        <p *ngIf="isVisible">This text is visible</p>
    `
})
export class ConditionalComponent {
    isVisible = true;
}
            

535. How do you use Angular's `ngSwitch` to conditionally display elements?

The `ngSwitch` directive allows you to conditionally display elements based on a switch value.


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

@Component({
    selector: 'app-switch',
    template: `
        <div [ngSwitch]="color">
            <p *ngSwitchCase="'red'">Red color</p>
            <p *ngSwitchCase="'green'">Green color</p>
            <p *ngSwitchDefault>Default color</p>
        </div>
    `
})
export class SwitchComponent {
    color = 'green';
}
            

536. How do you use Angular's `ngStyle` to dynamically set styles?

The `ngStyle` directive allows you to dynamically set CSS styles based on an object.


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

@Component({
    selector: 'app-style',
    template: `
        <div [ngStyle]="styles">Styled Div</div>
    `
})
export class StyleComponent {
    styles = {
        'color': 'blue',
        'font-size': '20px'
    };
}
            

537. How do you use Angular's `ngClass` to conditionally apply CSS classes?

The `ngClass` directive allows you to conditionally apply CSS classes based on an expression.


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

@Component({
    selector: 'app-class',
    template: `
        <div [ngClass]="{'active': isActive, 'inactive': !isActive}">Styled Div</div>
    `
})
export class ClassComponent {
    isActive = true;
}
            

538. How do you use Angular's `ngModel` to bind form inputs to component properties?

The `ngModel` directive is used for two-way data binding between form inputs and component properties.


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

@Component({
    selector: 'app-two-way-binding',
    template: `
        <input [(ngModel)]="name">
        <p>Hello, {{ name }}!</p>
    `
})
export class TwoWayBindingComponent {
    name: string = '';
}
            

539. How do you use Angular's `FormControl` to manage individual form controls?

The `FormControl` class is used to manage the state and validation of individual form controls.


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

@Component({
    selector: 'app-form-control',
    template: `
        <input [formControl]="nameControl">
        <p>Control Value: {{ nameControl.value }}</p>
    `
})
export class FormControlComponent {
    nameControl = new FormControl('');
}
            

540. How do you use Angular's `FormGroup` to manage a group of form controls?

The `FormGroup` class is used to group related `FormControl` instances into a single entity.


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

@Component({
    selector: 'app-form-group',
    template: `
        <form [formGroup]="form">
            <input formControlName="name">
            <input formControlName="email">
        </form>
    `
})
export class FormGroupComponent {
    form = new FormGroup({
        name: new FormControl(''),
        email: new FormControl('')
    });
}
            

 

Intermediate Angular Questions - Part 13

541. How do you use Angular's `@ViewChild` to access child components or DOM elements?

The `@ViewChild` decorator allows you to access child components or DOM elements from the parent component.


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

@Component({
    selector: 'app-child',
    template: `<p #childParagraph>Child Component</p>`
})
export class ChildComponent {}

@Component({
    selector: 'app-parent',
    template: `
        <app-child></app-child>
        <button (click)="logChildParagraph()">Log Child Paragraph</button>
    `
})
export class ParentComponent implements AfterViewInit {
    @ViewChild(ChildComponent) child!: ChildComponent;
    @ViewChild('childParagraph') childParagraph!: ElementRef;

    ngAfterViewInit() {
        console.log(this.child);
        console.log(this.childParagraph.nativeElement.textContent);
    }

    logChildParagraph() {
        console.log(this.childParagraph.nativeElement.textContent);
    }
}
            

542. How do you use Angular's `@ContentChild` to access projected content?

The `@ContentChild` decorator allows you to access content projected into the component using `ng-content`.


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

@Component({
    selector: 'app-card',
    template: `
        <ng-content></ng-content>
    `
})
export class CardComponent implements AfterContentInit {
    @ContentChild('cardContent') cardContent!: ElementRef;

    ngAfterContentInit() {
        console.log(this.cardContent.nativeElement.textContent);
    }
}

@Component({
    selector: 'app-root',
    template: `
        <app-card>
            </app-card><app-card><p #cardContent>Card Content</p>
        </app-card>
    `
})
export class AppComponent {}
            

543. How do you use Angular's `@Input` to pass data from a parent component to a child component?

The `@Input` decorator allows a parent component to pass data to a child component.


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

@Component({
    selector: 'app-child',
    template: `<p>Received: {{ data }}</p>`
})
export class ChildComponent {
    @Input() data!: string;
}

@Component({
    selector: 'app-parent',
    template: `<app-child [data]="parentData"></app-child>`
})
export class ParentComponent {
    parentData = 'Data from Parent';
}
            

544. How do you use Angular's `@Output` to emit custom events from a child component?

The `@Output` decorator is used to create custom events that a child component can emit to its parent.


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

@Component({
    selector: 'app-child',
    template: `<button (click)="sendMessage()">Send Message</button>`
})
export class ChildComponent {
    @Output() message = new EventEmitter<string>();

    sendMessage() {
        this.message.emit('Hello from Child');
    }
}

@Component({
    selector: 'app-parent',
    template: `<app-child (message)="receiveMessage($event)"></app-child>`
})
export class ParentComponent {
    receiveMessage(message: string) {
        console.log(message);
    }
}
            

545. How do you use Angular's `ReactiveForms` to create a form with validation?

The `ReactiveForms` module provides a way to create forms with validation using `FormGroup` and `FormControl`.


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

@Component({
    selector: 'app-reactive-form',
    template: `
        <form [formGroup]="form" (ngSubmit)="onSubmit()">
            <label for="label">Name:</label>
            <input id="label" formControlName="name">
            <div *ngIf="form.get('name')?.invalid && form.get('name')?.touched">
                Name is required.
            </div>
            <button type="submit">Submit</button>
        </form>
    `
})
export class ReactiveFormComponent {
    form = new FormGroup({
        name: new FormControl('', Validators.required)
    });

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

546. How do you use Angular's `ngFor` to display a list of items with a custom template?

The `ngFor` directive can be used with a custom template to display a list of items.


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

@Component({
    selector: 'app-item-list',
    template: `
        <ul>
            <ng-container *ngFor="let item of items; let i = index">
                </ng-container><ng-container *ngFor="let item of items; let i = index"><li>{{ i + 1 }}. {{ item }}</li>
            </ng-container>
        </ul>
    `
})
export class ItemListComponent {
    items = ['Item 1', 'Item 2', 'Item 3'];
}
            

547. How do you use Angular's `ngIf` with `else` to conditionally display content?

The `ngIf` directive can be used with the `else` clause to conditionally display alternate content.


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

@Component({
    selector: 'app-conditional',
    template: `
        <div *ngIf="isVisible; else elseBlock">
            <p>Content is visible</p>
        </div>
        <ng-template #elseBlock>
            </ng-template><ng-template #elseBlock><p>Content is hidden</p>
        </ng-template>
    `
})
export class ConditionalComponent {
    isVisible = true;
}
            

548. How do you use Angular's `ngSwitch` with multiple cases?

The `ngSwitch` directive can be used with multiple `ngSwitchCase` directives to handle different cases.


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

@Component({
    selector: 'app-switch',
    template: `
        <div [ngSwitch]="color">
            <p *ngSwitchCase="'red'">Red</p>
            <p *ngSwitchCase="'green'">Green</p>
            <p *ngSwitchCase="'blue'">Blue</p>
            <p *ngSwitchDefault>Unknown color</p>
        </div>
    `
})
export class SwitchComponent {
    color = 'green';
}
            

549. How do you use Angular's `ngStyle` to conditionally apply styles?

The `ngStyle` directive allows you to conditionally apply styles based on an object.


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

@Component({
    selector: 'app-style',
    template: `
        <div [ngStyle]="{ 'background-color': isActive ? 'yellow' : 'white' }">
            Conditional Style
        </div>
    `
})
export class StyleComponent {
    isActive = true;
}
            

550. How do you use Angular's `ngClass` to toggle multiple classes?

The `ngClass` directive allows you to toggle multiple CSS classes based on an object or array.


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

@Component({
    selector: 'app-class',
    template: `
        <div [ngClass]="{ 'active': isActive, 'highlight': isHighlighted }">Styled Div</div>
    `
})
export class ClassComponent {
    isActive = true;
    isHighlighted = false;
}
            

551. How do you use Angular's `ngModel` with forms to manage user input?

The `ngModel` directive is used for two-way data binding in forms.


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

@Component({
    selector: 'app-form',
    template: `
        <form>
            <label for="label">Name:</label>
            <input id="label" [(ngModel)]="name" name="name2">
            <p>Your name is {{ name }}</p>
        </form>
    `
})
export class FormComponent {
    name = '';
}
            

552. How do you use Angular's `FormBuilder` to create reactive forms?

The `FormBuilder` service helps in creating `FormGroup` and `FormControl` instances more easily.


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

@Component({
    selector: 'app-form-builder',
    template: `
        <form [formGroup]="form" (ngSubmit)="onSubmit()">
            <label for="email">Email:</label>
            <input id="email" formControlName="email">
            <div *ngIf="form.get('email')?.invalid && form.get('email')?.touched">
                Email is required.
            </div>
            <button type="submit">Submit</button>
        </form>
    `
})
export class FormBuilderComponent {
    form: FormGroup;

    constructor(private fb: FormBuilder) {
        this.form = this.fb.group({
            email: ['', Validators.required]
        });
    }

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

553. How do you use Angular's `FormArray` to handle dynamic form fields?

The `FormArray` class is used to handle an array of form controls or groups.


import { Component } from '@angular/core';
import { FormBuilder, FormArray, FormGroup } from '@angular/forms';

@Component({
    selector: 'app-form-array',
    template: `
        <form [formGroup]="form">
            <div formArrayName="items">
                <div *ngFor="let item of items.controls; let i = index">
                    <input [formControlName]="i">
                </div>
            </div>
            <button (click)="addItem()">Add Item</button>
        </form>
    `
})
export class FormArrayComponent {
    form: FormGroup;

    constructor(private fb: FormBuilder) {
        this.form = this.fb.group({
            items: this.fb.array([''])
        });
    }

    get items() {
        return this.form.get('items') as FormArray;
    }

    addItem() {
        this.items.push(this.fb.control(''));
    }
}
            

554. How do you use Angular's `AsyncPipe` to handle asynchronous data?

The `AsyncPipe` subscribes to an observable or promise and returns the latest value.


import { Component } from '@angular/core';
import { Observable, of } from 'rxjs';

@Component({
    selector: 'app-async',
    template: `
        <div *ngIf="data$ | async as data">
            {{ data }}
        </div>
    `
})
export class AsyncComponent {
    data$: Observable<string> = of('Asynchronous Data');
}
            

555. How do you use Angular's `ChangeDetectionStrategy` to optimize change detection?

The `ChangeDetectionStrategy` can be set to `OnPush` to optimize change detection by checking only when input properties change.


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

@Component({
    selector: 'app-on-push',
    template: `<p>OnPush Change Detection</p>`,
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class OnPushComponent {}
            

556. How do you use Angular's `@Injectable` to provide services in different scopes?

The `@Injectable` decorator is used to mark a class as available to be injected. Services can be provided at different levels, such as in the root or in a specific module.


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

@Injectable({
    providedIn: 'root' // or provide in a specific module
})
export class DataService {
    constructor() { }
}
            

557. How do you use Angular's `HttpClient` to make HTTP requests?

The `HttpClient` service is used to make HTTP requests and handle responses.


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

@Component({
    selector: 'app-http',
    template: `
        <button (click)="fetchData()">Fetch Data</button>
        <pre>{{ data | json }}
` }) export class HttpComponent { data: any; constructor(private http: HttpClient) { } fetchData() { this.http.get('https://api.example.com/data').subscribe(response => { this.data = response; }); } }

558. How do you use Angular's `Router` to navigate between routes?

The `Router` service is used to navigate between routes programmatically.


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

@Component({
    selector: 'app-navigation',
    template: `<button (click)="goToHome()">Go to Home</button>`
})
export class NavigationComponent {
    constructor(private router: Router) { }

    goToHome() {
        this.router.navigate(['/home']);
    }
}
            

559. How do you use Angular's `ActivatedRoute` to access route parameters?

The `ActivatedRoute` service is used to access route parameters and query parameters.


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

@Component({
    selector: 'app-route-params',
    template: `<p>Route Parameter: {{ id }}</p>`
})
export class RouteParamsComponent implements OnInit {
    id!: string;

    constructor(private route: ActivatedRoute) { }

    ngOnInit() {
        this.route.paramMap.subscribe(params => {
            this.id = params.get('id')!;
        });
    }
}
            

560. How do you use Angular's `RouterModule` to define and configure routes?

The `RouterModule` is used to define and configure routes in an Angular application.


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

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

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

 

Angular Intermediate Level Questions - Part 15

561. How do you create an Angular pipe and use it?

An Angular pipe is used to transform data in templates. You create a pipe by using the `@Pipe` decorator.


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

@Pipe({
    name: 'reverse'
})
export class ReversePipe implements PipeTransform {
    transform(value: string): string {
        return value.split('').reverse().join('');
    }
}
                

562. How do you create a custom Angular validator?

Custom validators can be created by implementing the `Validator` interface or by creating a function that returns a validator function.


import { AbstractControl, ValidatorFn } from '@angular/forms';

export function forbiddenNameValidator(nameRe: RegExp): ValidatorFn {
    return (control: AbstractControl): {[key: string]: any} | null => {
        const forbidden = nameRe.test(control.value);
        return forbidden ? { 'forbiddenName': { value: control.value } } : null;
    };
}
                

563. How do you use Angular's `@HostBinding` and `@HostListener` decorators?

`@HostBinding` binds a property of the host element, while `@HostListener` listens to events on the host element.


import { Directive, HostBinding, HostListener } from '@angular/core';

@Directive({
    selector: '[appHighlight]'
})
export class HighlightDirective {
    @HostBinding('style.backgroundColor') backgroundColor = 'transparent';

    @HostListener('mouseenter') onMouseEnter() {
        this.backgroundColor = 'yellow';
    }

    @HostListener('mouseleave') onMouseLeave() {
        this.backgroundColor = 'transparent';
    }
}
                

564. How do you use Angular's `ChangeDetectorRef` to manually trigger change detection?

`ChangeDetectorRef` is used to manually trigger change detection or detach the change detector.


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

@Component({
    selector: 'app-manual-change-detection',
    template: `
        <p>{{ data }}</p>
        <button (click)="updateData()">Update Data</button>
    `
})
export class ManualChangeDetectionComponent {
    data = 'Initial Data';

    constructor(private cdr: ChangeDetectorRef) {}

    updateData() {
        this.data = 'Updated Data';
        this.cdr.detectChanges(); // Manually trigger change detection
    }
}
                

565. How do you use Angular's `ngOnDestroy` lifecycle hook?

The `ngOnDestroy` lifecycle hook is used to clean up resources before the component is destroyed.


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

@Component({
    selector: 'app-cleanup',
    template: `<p>Cleanup Component</p>`
})
export class CleanupComponent implements OnDestroy {
    ngOnDestroy() {
        console.log('CleanupComponent destroyed');
        // Perform cleanup here
    }
}
                

566. How do you use Angular's `@ViewChild` to access child components or elements?

`@ViewChild` allows you to access a child component or DOM element in the parent component class.


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

@Component({
    selector: 'app-parent',
    template: `<app-child #child></app-child>`
})
export class ParentComponent {
    @ViewChild('child') childComponent!: ElementRef;

    ngAfterViewInit() {
        console.log(this.childComponent.nativeElement);
    }
}
                

567. How do you use Angular's `@ContentChild` to access projected content?

`@ContentChild` allows you to access projected content within a component.


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

@Component({
    selector: 'app-content',
    template: `<ng-content></ng-content>`
})
export class ContentComponent implements AfterContentInit {
    @ContentChild('content') content!: ElementRef;

    ngAfterContentInit() {
        console.log(this.content.nativeElement.textContent);
    }
}
                

568. How do you use Angular's `ngOnChanges` lifecycle hook?

The `ngOnChanges` lifecycle hook is used to detect changes to input properties.


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

@Component({
    selector: 'app-changes',
    template: `<p>Changes Component</p>`
})
export class ChangesComponent implements OnChanges {
    @Input() data!: string;

    ngOnChanges(changes: SimpleChanges) {
        console.log('Changes detected:', changes);
    }
}
                

569. How do you use Angular's `ngSwitch` to conditionally display content?

The `ngSwitch` directive is used to conditionally display content based on a switch expression.


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

@Component({
    selector: 'app-switch',
    template: `
        <div [ngSwitch]="condition">
            <p *ngSwitchCase="'A'">Case A</p>
            <p *ngSwitchCase="'B'">Case B</p>
            <p *ngSwitchDefault>Default Case</p>
        </div>
    `
})
export class SwitchComponent {
    condition = 'A';
}
                

570. How do you use Angular's `ngClass` to apply multiple CSS classes dynamically?

The `ngClass` directive allows you to apply multiple CSS classes dynamically based on component data.


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

@Component({
    selector: 'app-class',
    template: `
        <div [ngClass]="{ 'active': isActive, 'highlight': isHighlighted }">
            Conditional Classes
        </div>
    `
})
export class ClassComponent {
    isActive = true;
    isHighlighted = false;
}
                

571. How do you use Angular's `ng-template` to create reusable templates?

The `ng-template` directive allows you to define reusable templates.


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

@Component({
    selector: 'app-template',
    template: `
        <ng-template #myTemplate>
            </ng-template><ng-template #myTemplate><p>This is a reusable template</p>
        </ng-template>

        <ng-container *ngTemplateOutlet="myTemplate"></ng-container>
    `
})
export class TemplateComponent {}
                

572. How do you use Angular's `ngFor` with `trackBy` to improve performance?

The `trackBy` function helps Angular track items in a list for better performance.


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

@Component({
    selector: 'app-for',
    template: `
        <ul>
            <li *ngFor="let item of items; trackBy: trackById">{{ item.name }}</li>
        </ul>
    `
})
export class ForComponent {
    items = [{ id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }];

    trackById(index: number, item: any): number {
        return item.id;
    }
}
                

573. How do you use Angular's `ngModel` with two-way data binding?

The `ngModel` directive provides two-way data binding for form elements.


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

@Component({
    selector: 'app-model',
    template: `
        <input [(ngModel)]="name" placeholder="Enter your name">
        <p>Hello, {{ name }}!</p>
    `
})
export class ModelComponent {
    name = '';
}
                

574. How do you use Angular's `async` pipe in templates?

The `async` pipe subscribes to an Observable or Promise and returns the latest value.


import { Component } from '@angular/core';
import { Observable, of } from 'rxjs';

@Component({
    selector: 'app-async',
    template: `
        <div *ngIf="data$ | async as data">
            {{ data }}
        </div>
    `
})
export class AsyncComponent {
    data$: Observable<string> = of('Async Data');
}
                

575. How do you use Angular's `FormBuilder` to simplify form creation?

The `FormBuilder` service simplifies form creation with reactive forms.


import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
    selector: 'app-form-builder',
    template: `
        <form [formGroup]="form">
            <input formControlName="name" placeholder="Name">
            <button (click)="submit()">Submit</button>
        </form>
    `
})
export class FormBuilderComponent {
    form: FormGroup;

    constructor(private fb: FormBuilder) {
        this.form = this.fb.group({
            name: ['']
        });
    }

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

576. How do you use Angular's `HttpInterceptor` to modify HTTP requests and responses?

`HttpInterceptor` allows you to intercept and modify HTTP requests and responses.


import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const clonedReq = req.clone({ headers: req.headers.set('Authorization', 'Bearer token') });
        return next.handle(clonedReq);
    }
}
                

577. How do you use Angular's `Router` to navigate programmatically?

The `Router` service allows you to navigate programmatically within your application.


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

@Component({
    selector: 'app-navigate',
    template: `<button (click)="goToHome()">Go to Home</button>`
})
export class NavigateComponent {
    constructor(private router: Router) {}

    goToHome() {
        this.router.navigate(['/home']);
    }
}
                

578. How do you use Angular's `ng-container` to group elements without affecting layout?

`ng-container` is a logical container that doesn't affect the DOM layout.


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

@Component({
    selector: 'app-container',
    template: `
        <ng-container *ngIf="isVisible">
            </ng-container><ng-container *ngIf="isVisible"><p>Content is visible</p>
        </ng-container>
    `
})
export class ContainerComponent {
    isVisible = true;
}
                

579. How do you use Angular's `RouterModule` to configure routing?

The `RouterModule` is used to configure and manage routing in Angular applications.


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

const routes: Routes = [
    { path: 'home', component: HomeComponent },
    { path: 'about', component: AboutComponent },
    { path: '', redirectTo: '/home', pathMatch: 'full' }
];

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

580. How do you use Angular's `@Inject` to inject dependencies?

The `@Inject` decorator is used to specify a dependency to be injected.


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

@Component({
    selector: 'app-inject',
    template: `<p>Inject Component</p>`
})
export class InjectComponent {
    constructor(@Inject('API_URL') private apiUrl: string) {
        console.log(apiUrl);
    }
}
                

 

Angular Intermediate Level Questions - Part 16

581. How do you use Angular's `FormArray` to manage an array of form controls?

`FormArray` is used to manage an array of form controls in a reactive form.


import { Component } from '@angular/core';
import { FormBuilder, FormArray, FormGroup } from '@angular/forms';

@Component({
    selector: 'app-form-array',
    template: `
        <form [formGroup]="form">
            <div formArrayName="items">
                <div *ngFor="let item of items.controls; let i = index">
                    <input [formControlName]="i" placeholder="Item {{ i + 1 }}">
                </div>
            </div>
            <button (click)="addItem()">Add Item</button>
        </form>
    `
})
export class FormArrayComponent {
    form: FormGroup;

    get items(): FormArray {
        return this.form.get('items') as FormArray;
    }

    constructor(private fb: FormBuilder) {
        this.form = this.fb.group({
            items: this.fb.array([])
        });
    }

    addItem() {
        this.items.push(this.fb.control(''));
    }
}
                

582. How do you use Angular's `@Optional` decorator to handle optional dependencies?

The `@Optional` decorator allows you to inject dependencies that may or may not be available.


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

@Component({
    selector: 'app-optional',
    template: `<p>Optional Component</p>`
})
export class OptionalComponent {
    constructor(@Optional() private optionalService?: SomeService) {
        if (this.optionalService) {
            // Use the service
        } else {
            // Handle the absence of the service
        }
    }
}
                

583. How do you use Angular's `NgZone` to run code inside or outside Angular's zone?

`NgZone` allows you to run code inside or outside Angular's change detection zone.


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

@Component({
    selector: 'app-zone',
    template: `<p>Zone Component</p>`
})
export class ZoneComponent {
    constructor(private ngZone: NgZone) {
        this.ngZone.runOutsideAngular(() => {
            // Code running outside Angular's zone
            console.log('Outside Angular Zone');
            // Simulate an async operation
            setTimeout(() => {
                this.ngZone.run(() => {
                    console.log('Back inside Angular Zone');
                });
            }, 1000);
        });
    }
}
                

584. How do you use Angular's `@Injectable` decorator with providedIn?

The `@Injectable` decorator with `providedIn` allows you to specify the provider scope for a service.


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

@Injectable({
    providedIn: 'root' // Service is available throughout the app
})
export class MyService {
    constructor() {}
}
                

585. How do you use Angular's `@ContentChildren` to access multiple projected content elements?

`@ContentChildren` is used to access multiple projected content elements.


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

@Component({
    selector: 'app-content',
    template: `
        <ng-content></ng-content>
    `
})
export class ContentComponent implements AfterContentInit {
    @ContentChildren('content') contents!: QueryList<ElementRef>;

    ngAfterContentInit() {
        this.contents.forEach(content => {
            console.log(content.nativeElement.textContent);
        });
    }
}
                

586. How do you use Angular's `@Host` decorator to inject a dependency from the host element?

The `@Host` decorator allows you to inject a dependency from the host element.


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

@Component({
    selector: 'app-host',
    template: `<p>Host Component</p>`
})
export class HostComponent {
    constructor(@Host() private parentComponent: ParentComponent) {
        console.log(this.parentComponent);
    }
}
                

587. How do you use Angular's `@Input` and `@Output` decorators to pass data between components?

`@Input` and `@Output` are used to pass data between parent and child components.


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

@Component({
    selector: 'app-child',
    template: `
        <p>{{ data }}</p>
        <button (click)="sendData()">Send Data</button>
    `
})
export class ChildComponent {
    @Input() data!: string;
    @Output() dataChange = new EventEmitter<string>();

    sendData() {
        this.dataChange.emit('New Data');
    }
}

@Component({
    selector: 'app-parent',
    template: `
        <app-child [data]="parentData" (dataChange)="handleDataChange($event)"></app-child>
    `
})
export class ParentComponent {
    parentData = 'Initial Data';

    handleDataChange(newData: string) {
        this.parentData = newData;
    }
}
                

588. How do you use Angular's `@Inject` decorator to inject tokens?

The `@Inject` decorator is used to inject tokens for dependency injection.


import { InjectionToken, Injectable, Inject } from '@angular/core';

export const API_URL = new InjectionToken<string>('apiUrl');

@Injectable({
    providedIn: 'root'
})
export class ApiService {
    constructor(@Inject(API_URL) private apiUrl: string) {
        console.log(apiUrl);
    }
}
                

589. How do you use Angular's `ngIf` with `else` to handle conditional templates?

`ngIf` with `else` allows you to handle conditional templates more elegantly.


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

@Component({
    selector: 'app-if-else',
    template: `
        <ng-container *ngIf="isVisible; else elseBlock">
            </ng-container><ng-container *ngIf="isVisible; else elseBlock"><p>Visible</p>
        </ng-container>
        <ng-template #elseBlock>
            </ng-template><ng-template #elseBlock><p>Not Visible</p>
        </ng-template>
    `
})
export class IfElseComponent {
    isVisible = true;
}
                

590. How do you use Angular's `ngFor` with `index` to display item indexes?

`ngFor` with `index` allows you to display the index of items in a list.


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

@Component({
    selector: 'app-for-index',
    template: `
        <ul>
            <li *ngFor="let item of items; let i = index">
                {{ i + 1 }}. {{ item }}
            </li>
        </ul>
    `
})
export class ForIndexComponent {
    items = ['Item 1', 'Item 2', 'Item 3'];
}
                

591. How do you use Angular's `@ViewChild` to access a child component or element?

`@ViewChild` allows you to access a child component or element in the template.


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

@Component({
    selector: 'app-view-child',
    template: `
        <div #content>Content</div>
    `
})
export class ViewChildComponent implements AfterViewInit {
    @ViewChild('content') content!: ElementRef;

    ngAfterViewInit() {
        console.log(this.content.nativeElement.textContent);
    }
}
                

592. How do you use Angular's `ngClass` to conditionally apply CSS classes?

`ngClass` is used to conditionally apply CSS classes based on expressions.


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

@Component({
    selector: 'app-class',
    template: `
        <div [ngClass]="{ 'active': isActive, 'disabled': !isActive }">
            Conditional Classes
        </div>
    `
})
export class ClassComponent {
    isActive = true;
}
                

593. How do you use Angular's `ngStyle` to apply inline styles dynamically?

`ngStyle` allows you to apply inline styles dynamically based on expressions.


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

@Component({
    selector: 'app-style',
    template: `
        <div [ngStyle]="{ 'color': color, 'font-size': fontSize + 'px' }">
            Dynamic Styles
        </div>
    `
})
export class StyleComponent {
    color = 'blue';
    fontSize = 16;
}
                

594. How do you use Angular's `@HostListener` to listen to DOM events?

The `@HostListener` decorator allows you to listen to DOM events on the host element.


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

@Component({
    selector: 'app-host-listener',
    template: `<p>Host Listener Component</p>`
})
export class HostListenerComponent {
    @HostListener('click', ['$event'])
    onClick(event: Event) {
        console.log('Element clicked', event);
    }
}
                

595. How do you use Angular's `ChangeDetectorRef` to manually trigger change detection?

`ChangeDetectorRef` allows you to manually trigger change detection in Angular.


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

@Component({
    selector: 'app-change-detector',
    template: `<p>Change Detector Component</p>`
})
export class ChangeDetectorComponent {
    constructor(private cdr: ChangeDetectorRef) {}

    triggerChangeDetection() {
        this.cdr.detectChanges();
    }
}
                

596. How do you use Angular's `@Directive` to create a custom directive?

The `@Directive` decorator is used to create custom directives.


import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';

@Directive({
    selector: '[appHighlight]'
})
export class HighlightDirective {
    constructor(private el: ElementRef, private renderer: Renderer2) {}

    @HostListener('mouseenter') onMouseEnter() {
        this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow');
    }

    @HostListener('mouseleave') onMouseLeave() {
        this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'transparent');
    }
}
                

597. How do you use Angular's `@Pipe` to create a custom pipe?

The `@Pipe` decorator is used to create custom pipes.


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

@Pipe({
    name: 'reverse'
})
export class ReversePipe implements PipeTransform {
    transform(value: string): string {
        return value.split('').reverse().join('');
    }
}
                

598. How do you use Angular's `@NgModule` to define module metadata?

The `@NgModule` decorator is used to define the metadata for an Angular module.


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

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

599. How do you use Angular's `Router` to define nested routes?

Nested routes can be defined using child routes in the Angular Router configuration.


import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { ParentComponent } from './parent.component';
import { ChildComponent } from './child.component';

const routes: Routes = [
    { path: 'parent', component: ParentComponent, children: [
        { path: 'child', component: ChildComponent }
    ]}
];

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

600. How do you use Angular's `@NgModule` to import and export modules?

The `@NgModule` decorator allows you to import and export modules within your application.


import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';

@NgModule({
    imports: [CommonModule, FormsModule],
    exports: [CommonModule, FormsModule]
})
export class SharedModule {}
                

Angular Intermediate Level Questions - Part 17

601. How do you use Angular's `ngSwitch` directive to conditionally display content?

`ngSwitch` allows you to conditionally display content based on an expression.


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

@Component({
    selector: 'app-switch',
    template: `
        <div [ngSwitch]="color">
            <p *ngSwitchCase="'red'">Red</p>
            <p *ngSwitchCase="'green'">Green</p>
            <p *ngSwitchDefault>Default</p>
        </div>
    `
})
export class SwitchComponent {
    color = 'green';
}
                

602. How do you use Angular's `ngIf` with `then` to handle conditional templates?

`ngIf` with `then` allows you to specify a template to display when the condition is true.


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

@Component({
    selector: 'app-if-then',
    template: `
        <ng-container *ngIf="isVisible; then thenBlock; else elseBlock"></ng-container>
        <ng-template #thenBlock>
            </ng-template><ng-template #thenBlock><p>Visible</p>
        </ng-template>
        <ng-template #elseBlock>
            </ng-template><ng-template #elseBlock><p>Not Visible</p>
        </ng-template>
    `
})
export class IfThenComponent {
    isVisible = true;
}
                

603. How do you use Angular's `ngFor` to iterate over objects?

`ngFor` can be used to iterate over objects and access their properties.


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

@Component({
    selector: 'app-for-object',
    template: `
        <ul>
            <li *ngFor="let key of objectKeys(myObject)">
                {{ key }}: {{ myObject[key] }}
            </li>
        </ul>
    `
})
export class ForObjectComponent {
    myObject = { name: 'Alice', age: 30, city: 'New York' };

    objectKeys(obj: any) {
        return Object.keys(obj);
    }
}
                

604. How do you use Angular's `@Injectable` decorator to create a service with a custom provider?

`@Injectable` can be used with custom providers to configure service injection.


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

export const API_URL = new InjectionToken<string>('apiUrl');

@Injectable({
    providedIn: 'root'
})
export class ApiService {
    constructor(@Inject(API_URL) private apiUrl: string) {}
}
                

605. How do you use Angular's `@ViewChild` with static options to access child components?

`@ViewChild` with `static: true` allows access to child components before the view initialization.


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

@Component({
    selector: 'app-static-view-child',
    template: `
        <div #content>Static View Child Content</div>
    `
})
export class StaticViewChildComponent implements AfterViewInit {
    @ViewChild('content', { static: true }) content!: ElementRef;

    ngAfterViewInit() {
        console.log(this.content.nativeElement.textContent);
    }
}
                

606. How do you use Angular's `@Output` with `EventEmitter` to emit custom events?

`@Output` with `EventEmitter` allows you to emit custom events from a child component.


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

@Component({
    selector: 'app-output',
    template: `
        <button (click)="notifyParent()">Notify Parent</button>
    `
})
export class OutputComponent {
    @Output() notify = new EventEmitter<string>();

    notifyParent() {
        this.notify.emit('Hello from child!');
    }
}

@Component({
    selector: 'app-parent',
    template: `
        <app-output (notify)="handleNotification($event)"></app-output>
        <p>{{ message }}</p>
    `
})
export class ParentComponent {
    message = '';

    handleNotification(msg: string) {
        this.message = msg;
    }
}
                

607. How do you use Angular's `NgModule` with lazy loading to load modules on demand?

Lazy loading is implemented using the `loadChildren` property in the route configuration.


import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

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

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

608. How do you use Angular's `NgZone` to manage change detection manually?

`NgZone` allows you to manage Angular's change detection manually.


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

@Component({
    selector: 'app-zone',
    template: `<p>Zone Component</p>`
})
export class ZoneComponent {
    constructor(private ngZone: NgZone) {}

    runOutsideAngular() {
        this.ngZone.runOutsideAngular(() => {
            // Code running outside Angular's zone
            console.log('Running outside Angular zone');
            setTimeout(() => {
                this.ngZone.run(() => {
                    console.log('Running inside Angular zone');
                });
            }, 1000);
        });
    }
}
                

609. How do you use Angular's `ChangeDetectorRef` to trigger change detection?

`ChangeDetectorRef` is used to manually trigger change detection.


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

@Component({
    selector: 'app-change-detector',
    template: `<p>Change Detector Component</p>`
})
export class ChangeDetectorComponent {
    constructor(private cdr: ChangeDetectorRef) {}

    triggerChangeDetection() {
        this.cdr.detectChanges();
    }
}
                

610. How do you use Angular's `@HostBinding` to bind properties to the host element?

`@HostBinding` allows you to bind properties to the host element of a directive or component.


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

@Directive({
    selector: '[appHostBinding]'
})
export class HostBindingDirective {
    @HostBinding('class.active') isActive = true;
}
                

611. How do you use Angular's `@HostListener` to listen to events on the host element?

`@HostListener` is used to listen to events on the host element.


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

@Directive({
    selector: '[appHostListener]'
})
export class HostListenerDirective {
    @HostListener('click', ['$event'])
    onClick(event: Event) {
        console.log('Host element clicked', event);
    }
}
                

612. How do you use Angular's `@Input` and `@Output` decorators together to pass data between components?

`@Input` is used to pass data to a child component, while `@Output` is used to emit events from the child component.


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

@Component({
    selector: 'app-child',
    template: `
        <p>{{ data }}</p>
        <button (click)="notifyParent()">Notify Parent</button>
    `
})
export class ChildComponent {
    @Input() data!: string;
    @Output() notify = new EventEmitter<void>();

    notifyParent() {
        this.notify.emit();
    }
}

@Component({
    selector: 'app-parent',
    template: `
        <app-child [data]="parentData" (notify)="handleNotification()"></app-child>
        <p>{{ message }}</p>
    `
})
export class ParentComponent {
    parentData = 'Data from parent';
    message = '';

    handleNotification() {
        this.message = 'Child component notified!';
    }
}
                

613. How do you use Angular's `Router` to handle route parameters?

The `Router` allows you to handle route parameters using route configuration and activated route service.


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

@Component({
    selector: 'app-route-param',
    template: `<p>Route Param: {{ id }}</p>`
})
export class RouteParamComponent implements OnInit {
    id!: string;

    constructor(private route: ActivatedRoute) {}

    ngOnInit() {
        this.route.paramMap.subscribe(params => {
            this.id = params.get('id') || '';
        });
    }
}

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { RouteParamComponent } from './route-param.component';

const routes: Routes = [
    { path: 'param/:id', component: RouteParamComponent }
];

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

614. How do you use Angular's `Router` to define route guards?

Route guards are used to control access to routes based on conditions.


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

@Injectable({
    providedIn: 'root'
})
export class AuthGuard implements CanActivate {
    constructor(private router: Router) {}

    canActivate(): boolean {
        const isLoggedIn = false; // Replace with real authentication check
        if (!isLoggedIn) {
            this.router.navigate(['/login']);
            return false;
        }
        return true;
    }
}

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AuthGuard } from './auth.guard';
import { HomeComponent } from './home.component';
import { LoginComponent } from './login.component';

const routes: Routes = [
    { path: '', component: HomeComponent },
    { path: 'login', component: LoginComponent },
    { path: 'protected', component: ProtectedComponent, canActivate: [AuthGuard] }
];

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

615. How do you use Angular's `NgModule` to define module dependencies?

Module dependencies are defined using the `imports` array in the `@NgModule` decorator.


import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';

@NgModule({
    imports: [CommonModule, FormsModule],
    declarations: [SomeComponent],
    exports: [SomeComponent]
})
export class SomeModule {}
                

616. How do you use Angular's `@Component` decorator to configure component metadata?

The `@Component` decorator is used to configure metadata such as selector, template, and styles.


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

@Component({
    selector: 'app-example',
    template: `<p>Example Component</p>`,
    styles: [`p { color: blue; }`]
})
export class ExampleComponent {}
                

617. How do you use Angular's `@NgModule` to create a feature module?

A feature module is created using `@NgModule` to group related components, directives, and services.


import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FeatureComponent } from './feature.component';

@NgModule({
    imports: [CommonModule],
    declarations: [FeatureComponent],
    exports: [FeatureComponent]
})
export class FeatureModule {}
                

618. How do you use Angular's `@Inject` to inject dependencies into a service?

`@Inject` is used to specify a custom provider for dependency injection.


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

export const API_URL = new InjectionToken<string>('apiUrl');

@Injectable({
    providedIn: 'root'
})
export class ApiService {
    constructor(@Inject(API_URL) private apiUrl: string) {}
}
                

619. How do you use Angular's `@NgModule` to define module imports and providers?

Module imports and providers are defined using the `imports` and `providers` arrays in `@NgModule`.


import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SomeService } from './some.service';

@NgModule({
    imports: [CommonModule],
    providers: [SomeService]
})
export class SharedModule {}
                

620. How do you use Angular's `@Component` to define component templates and styles?

The `@Component` decorator defines component templates and styles using `template` and `styles` properties.


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

@Component({
    selector: 'app-example',
    template: `<div>Hello World</div>`,
    styles: [`div { color: red; }`]
})
export class ExampleComponent {}
                

 

Angular Intermediate Level Questions - Part 18

621. How do you use Angular's `HttpClient` to make HTTP GET requests?

`HttpClient` is used to make HTTP GET requests and handle responses.


import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';

@Component({
    selector: 'app-http-get',
    template: `<p>Data: {{ data | json }}</p>`
})
export class HttpGetComponent implements OnInit {
    data: any;

    constructor(private http: HttpClient) {}

    ngOnInit() {
        this.http.get('https://api.example.com/data').subscribe(response => {
            this.data = response;
        });
    }
}
                

622. How do you use Angular's `HttpClient` to make HTTP POST requests?

`HttpClient` is used to make HTTP POST requests to send data to the server.


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

@Component({
    selector: 'app-http-post',
    template: `<button (click)="sendData()">Send Data</button>`
})
export class HttpPostComponent {
    constructor(private http: HttpClient) {}

    sendData() {
        const payload = { key: 'value' };
        this.http.post('https://api.example.com/submit', payload).subscribe(response => {
            console.log('Response:', response);
        });
    }
}
                

623. How do you use Angular's `HttpClient` to handle query parameters?

Query parameters can be handled using the `params` option in `HttpClient` methods.


import { HttpClient, HttpParams } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';

@Component({
    selector: 'app-http-params',
    template: `<p>Data: {{ data | json }}</p>`
})
export class HttpParamsComponent implements OnInit {
    data: any;

    constructor(private http: HttpClient) {}

    ngOnInit() {
        let params = new HttpParams().set('param1', 'value1');
        this.http.get('https://api.example.com/data', { params }).subscribe(response => {
            this.data = response;
        });
    }
}
                

624. How do you use Angular's `HttpInterceptor` to add headers to HTTP requests?

`HttpInterceptor` allows you to modify HTTP requests and responses globally.


import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const authReq = req.clone({
            setHeaders: { Authorization: 'Bearer token' }
        });
        return next.handle(authReq);
    }
}
                

625. How do you use Angular's `HttpClient` to handle HTTP errors?

Errors in HTTP requests can be handled using RxJS operators like `catchError`.


import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs';

@Component({
    selector: 'app-http-error',
    template: `<p>Error: {{ errorMessage }}</p>`
})
export class HttpErrorComponent {
    errorMessage: string = '';

    constructor(private http: HttpClient) {}

    makeRequest() {
        this.http.get('https://api.example.com/data').pipe(
            catchError(error => {
                this.errorMessage = 'An error occurred!';
                return of([]);
            })
        ).subscribe();
    }
}
                

626. How do you use Angular's `NgForm` to handle form validation?

`NgForm` provides form validation and status management.


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

@Component({
    selector: 'app-form-validation',
    template: `
        <form #myForm="ngForm" (ngSubmit)="onSubmit(myForm)">
            <input name="name3" ngModel required>
            <button type="submit" [disabled]="myForm.invalid">Submit</button>
        </form>
    `
})
export class FormValidationComponent {
    onSubmit(form: NgForm) {
        if (form.valid) {
            console.log('Form Submitted!', form.value);
        }
    }
}
                

627. How do you use Angular's `FormBuilder` to create reactive forms?

`FormBuilder` is used to create reactive forms with validators.


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

@Component({
    selector: 'app-reactive-form',
    template: `
        <form [formGroup]="myForm" (ngSubmit)="onSubmit()">
            <input formControlName="name">
            <button type="submit" [disabled]="myForm.invalid">Submit</button>
        </form>
    `
})
export class ReactiveFormComponent {
    myForm: FormGroup;

    constructor(private fb: FormBuilder) {
        this.myForm = this.fb.group({
            name: ['', Validators.required]
        });
    }

    onSubmit() {
        if (this.myForm.valid) {
            console.log('Form Submitted!', this.myForm.value);
        }
    }
}
                

628. How do you use Angular's `FormControl` to handle form fields?

`FormControl` is used to manage the value and validation of individual form fields.


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

@Component({
    selector: 'app-form-control',
    template: `
        <input [formControl]="nameControl">
        <p *ngIf="nameControl.invalid && (nameControl.dirty || nameControl.touched)">
            Name is required
        </p>
    `
})
export class FormControlComponent {
    nameControl = new FormControl('', Validators.required);
}
                

629. How do you use Angular's `FormArray` to handle dynamic form fields?

`FormArray` allows you to manage an array of form controls or groups dynamically.


import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormArray, Validators } from '@angular/forms';

@Component({
    selector: 'app-form-array',
    template: `
        <form [formGroup]="myForm" (ngSubmit)="onSubmit()">
            <div formArrayName="items">
                <div *ngFor="let item of items.controls; let i = index">
                    <input [formControlName]="i">
                </div>
            </div>
            <button type="button" (click)="addItem()">Add Item</button>
            <button type="submit" [disabled]="myForm.invalid">Submit</button>
        </form>
    `
})
export class FormArrayComponent {
    myForm: FormGroup;

    get items() {
        return this.myForm.get('items') as FormArray;
    }

    constructor(private fb: FormBuilder) {
        this.myForm = this.fb.group({
            items: this.fb.array([this.fb.control('', Validators.required)])
        });
    }

    addItem() {
        this.items.push(this.fb.control('', Validators.required));
    }

    onSubmit() {
        if (this.myForm.valid) {
            console.log('Form Submitted!', this.myForm.value);
        }
    }
}
                

630. How do you use Angular's `ngFor` directive to iterate over a list of items?

`ngFor` is used to iterate over a list and render a template for each item.


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

@Component({
    selector: 'app-ng-for',
    template: `
        <ul>
            <li *ngFor="let item of items">{{ item }}</li>
        </ul>
    `
})
export class NgForComponent {
    items = ['Item 1', 'Item 2', 'Item 3'];
}
                

631. How do you use Angular's `ngIf` directive to conditionally render elements?

`ngIf` is used to conditionally include or exclude elements from the DOM.


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

@Component({
    selector: 'app-ng-if',
    template: `
        <div *ngIf="isVisible">Visible content</div>
        <button (click)="toggleVisibility()">Toggle Visibility</button>
    `
})
export class NgIfComponent {
    isVisible = true;

    toggleVisibility() {
        this.isVisible = !this.isVisible;
    }
}
                

632. How do you use Angular's `ngSwitch` directive to conditionally render elements?

`ngSwitch` is used to conditionally include or exclude elements based on a switch expression.


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

@Component({
    selector: 'app-ng-switch',
    template: `
        <div [ngSwitch]="selectedOption">
            <div *ngSwitchCase="'option1'">Option 1 content</div>
            <div *ngSwitchCase="'option2'">Option 2 content</div>
            <div *ngSwitchDefault>Default content</div>
        </div>
        <button (click)="selectOption('option1')">Select Option 1</button>
        <button (click)="selectOption('option2')">Select Option 2</button>
    `
})
export class NgSwitchComponent {
    selectedOption = 'option1';

    selectOption(option: string) {
        this.selectedOption = option;
    }
}
                

633. How do you use Angular's `ngClass` directive to conditionally apply CSS classes?

`ngClass` allows you to conditionally apply CSS classes to elements based on an expression.


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

@Component({
    selector: 'app-ng-class',
    template: `
        <div [ngClass]="{ 'active': isActive, 'inactive': !isActive }">Content</div>
        <button (click)="toggleStatus()">Toggle Status</button>
    `,
    styles: [`
        .active { color: green; }
        .inactive { color: red; }
    `]
})
export class NgClassComponent {
    isActive = true;

    toggleStatus() {
        this.isActive = !this.isActive;
    }
}
                

634. How do you use Angular's `ngStyle` directive to conditionally apply inline styles?

`ngStyle` allows you to conditionally apply inline styles to elements based on an expression.


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

@Component({
    selector: 'app-ng-style',
    template: `
        <div [ngStyle]="{ 'color': isActive ? 'green' : 'red' }">Styled Content</div>
        <button (click)="toggleStatus()">Toggle Status</button>
    `
})
export class NgStyleComponent {
    isActive = true;

    toggleStatus() {
        this.isActive = !this.isActive;
    }
}
                

635. How do you use Angular's `ng-container` to group elements without adding extra DOM nodes?

`ng-container` is used to group elements and apply structural directives without adding extra DOM nodes.


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

@Component({
    selector: 'app-ng-container',
    template: `
        <ng-container *ngIf="isVisible">
            </ng-container><ng-container *ngIf="isVisible"><p>Visible Content 1</p>
            <p>Visible Content 2</p>
        </ng-container>
    `
})
export class NgContainerComponent {
    isVisible = true;
}
                

636. How do you use Angular's `ngModel` to two-way bind data?

`ngModel` provides two-way data binding between the view and the component.


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

@Component({
    selector: 'app-ng-model',
    template: `
        <input [(ngModel)]="data">
        <p>Data: {{ data }}</p>
    `
})
export class NgModelComponent {
    data = 'Initial value';
}
                

637. How do you use Angular's `@ViewChild` to access child components or DOM elements?

`@ViewChild` allows you to access child components or DOM elements directly from the parent component.


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

@Component({
    selector: 'app-view-child',
    template: `
        <div #myDiv>Content</div>
        <button (click)="changeContent()">Change Content</button>
    `
})
export class ViewChildComponent implements AfterViewInit {
    @ViewChild('myDiv') myDiv!: ElementRef;

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

    changeContent() {
        this.myDiv.nativeElement.textContent = 'New Content';
    }
}
                

638. How do you use Angular's `@ContentChild` to access projected content?

`@ContentChild` allows you to access projected content inside a component.


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

@Component({
    selector: 'app-content-child',
    template: `<ng-content></ng-content>`
})
export class ContentChildComponent implements AfterContentInit {
    @ContentChild('projectedContent') projectedContent!: ElementRef;

    ngAfterContentInit() {
        console.log(this.projectedContent.nativeElement.textContent);
    }
}

@Component({
    selector: 'app-root',
    template: `
        <app-content-child>
            </app-content-child><app-content-child><div #projectedContent>Projected Content</div>
        </app-content-child>
    `
})
export class AppComponent {}
                

639. How do you use Angular's `@HostListener` to listen to DOM events?

`@HostListener` is used to listen to DOM events on the host element of the directive or component.


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

@Directive({
    selector: '[appHostListener]'
})
export class HostListenerDirective {
    @HostListener('click', ['$event'])
    onClick(event: Event) {
        console.log('Host element clicked', event);
    }
}
                

640. How do you use Angular's `@Input` and `@Output` decorators together to pass data between components?

`@Input` is used to pass data to a child component, while `@Output` is used to emit events from the child component.


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

@Component({
    selector: 'app-child',
    template: `
        <button (click)="notifyParent()">Notify Parent</button>
    `
})
export class ChildComponent {
    @Input() data: string = '';
    @Output() notify: EventEmitter<void> = new EventEmitter<void>();

    notifyParent() {
        this.notify.emit();
    }
}

@Component({
    selector: 'app-parent',
    template: `
        <app-child [data]="parentData" (notify)="handleNotification()"></app-child>
        <p>Received Data: {{ receivedData }}</p>
    `
})
export class ParentComponent {
    parentData = 'Data from parent';
    receivedData = '';

    handleNotification() {
        this.receivedData = 'Notification received from child!';
    }
}
                

641. How do you model a FormArray of nested FormGroup for invoice line items?

Use FormBuilder.array containing FormGroup instances so each row keeps its own controls and validation.

items = this.fb.array([
  this.fb.group({ name: [''], qty: [1, Validators.min(1)], price: [0] })
]);

get itemsArray(): FormArray {
  return this.form.get('items') as FormArray;
}

642. How do you insert and remove controls in a FormArray at a specific index?

Call insert(index, control) to add a row and removeAt(index) to delete one, then recompute derived totals if needed.

addItem(index = this.itemsArray.length) {
  this.itemsArray.insert(index, this.fb.group({ name: [''], qty: [1], price: [0] }));
}

removeItem(index: number) {
  this.itemsArray.removeAt(index);
}

643. How do you patch a reactive form from an API response that includes nested arrays?

Build the empty FormArray shape first, then call patchValue (or setValue) so nested groups and arrays align with the response structure.

this.http.get<Invoice>('/api/invoice/1').subscribe(data => {
  this.form.patchValue(data);
  // or rebuild items array explicitly when lengths differ
});

644. How do you validate an entire FormArray, such as requiring at least one item?

Attach a validator to the FormArray itself (not only children) and check controls.length.

items = this.fb.array([], (arr: AbstractControl) =>
  arr.value?.length ? null : { minItems: true }
);

645. How do you implement cross-field validation between two controls in the same group?

Apply the validator at the FormGroup level and compare sibling control values in the validator function.

this.fb.group({
  password: [''],
  confirm: ['']
}, { validators: (g: AbstractControl) =>
  g.get('password')?.value === g.get('confirm')?.value ? null : { mismatch: true }
});

646. How do you write and register a custom synchronous validator?

Create a function returning ValidationErrors | null, then pass it in the control's validator array.

function noSpaces(control: AbstractControl): ValidationErrors | null {
  return /\s/.test(control.value) ? { noSpaces: true } : null;
}

this.fb.control('', [Validators.required, noSpaces]);

647. How do you add an asynchronous validator that checks username availability?

Return an observable that emits validation errors or null, and wire it as the async validator (third argument).

username: ['', [Validators.required], [this.checkUsername.bind(this)]]

checkUsername(control: AbstractControl): Observable<ValidationErrors | null> {
  return this.http.get(`/api/check/${control.value}`).pipe(
    map(res => res.available ? null : { taken: true }),
    catchError(() => of(null))
  );
}

648. How do you react to overall form status changes (VALID, INVALID, PENDING, DISABLED)?

Subscribe to the form's statusChanges observable and update UI state accordingly.

this.form.statusChanges.subscribe(status => {
  this.isSaving = status === 'PENDING';
  this.canSubmit = status === 'VALID';
});

649. How do disabled controls affect form value and submission?

Disabled controls are excluded from value, but getRawValue() includes them. Toggle state with disable() and enable(), and prefer raw value when submitting data that includes disabled fields.

this.form.get('legacyField')?.disable();
const payload = this.form.getRawValue(); // includes disabled controls

650. How do you use valueChanges to implement dependent or derived fields?

Subscribe to a control's valueChanges, apply transformations, and update related controls without triggering infinite loops.

this.form.get('qty')?.valueChanges.subscribe(qty => {
  const price = this.form.get('price')?.value ?? 0;
  this.form.get('total')?.setValue(qty * price, { emitEvent: false });
});

651. What does switchMap do when a new source value arrives while the previous inner observable is still active?

It cancels (unsubscribes from) the previous inner observable and starts a new one from the latest value. This prevents stale results and is ideal for typeahead search or route-param-driven data loading.

this.route.params.pipe(
  switchMap(params => this.userService.getUser(params['id']))
).subscribe(user => this.user = user);

652. When is mergeMap the better choice over switchMap?

Use mergeMap when every source emission must be processed concurrently and none should be cancelled, such as firing parallel HTTP requests for each item in a stream or handling independent user actions.

this.actions$.pipe(
  mergeMap(action => this.api.perform(action))
).subscribe(result => this.handle(result));

653. How does concatMap differ from mergeMap in execution order?

concatMap queues inner observables and runs them one at a time in source order, waiting for each to complete before starting the next. Use it when order and sequential processing matter, like ordered saves or chained API calls.

this.queue$.pipe(
  concatMap(item => this.api.save(item))
).subscribe(saved => console.log('saved', saved));

654. What problem does exhaustMap solve that the other flattening operators do not?

exhaustMap ignores new source emissions while an inner observable is still running, preventing duplicate submissions. It is ideal for login buttons or form submits where repeated clicks should not trigger parallel requests.

fromEvent(this.submitBtn, 'click').pipe(
  exhaustMap(() => this.api.submitForm(this.form.value))
).subscribe(res => this.onSuccess(res));

655. How do debounceTime and distinctUntilChanged combine for an efficient search input?

debounceTime waits for a pause in typing before emitting, and distinctUntilChanged skips emissions identical to the previous value, avoiding duplicate network requests for the same query.

this.searchControl.valueChanges.pipe(
  debounceTime(400),
  distinctUntilChanged(),
  switchMap(term => this.api.search(term))
).subscribe(results => this.results = results);

656. What is shareReplay used for and what does its bufferSize/refCount control?

shareReplay multicasts a source to multiple subscribers and replays the last N emissions to late subscribers. bufferSize sets how many values are replayed; refCount controls whether the source unsubscribes when subscriber count hits zero.

readonly config$ = this.http.get('/api/config').pipe(
  shareReplay({ bufferSize: 1, refCount: true })
);

657. How should catchError and retry work together to handle transient HTTP failures?

retry resubscribes to the source a given number of times on error; catchError catches the final error and returns a fallback observable (or rethrows). Order matters: place retry before catchError so retries happen before the fallback.

this.http.get('/api/data').pipe(
  retry(2),
  catchError(err => {
    console.error(err);
    return of([]);
  })
).subscribe(data => this.data = data);

658. Why use takeUntil with a destroy$ subject instead of ngOnDestroy alone?

takeUntil automatically completes the observable when destroy$ emits, preventing memory leaks and late emissions after component destruction. finalize can run cleanup logic when the stream completes or errors.

private destroy$ = new Subject<void>();
ngOnInit() {
  this.service.data$.pipe(
    takeUntil(this.destroy$),
    finalize(() => console.log('cleaned up'))
  ).subscribe(d => this.data = d);
}
ngOnDestroy() { this.destroy$.next(); this.destroy$.complete(); }

659. When should you use forkJoin versus combineLatest?

forkJoin waits for all source observables to complete and emits their last values once; use it for parallel HTTP requests. combineLatest emits whenever any source emits, using the latest value from each; use it for reactive forms or live UI state.

forkJoin({
  users: this.api.getUsers(),
  roles: this.api.getRoles()
}).subscribe(({ users, roles }) => this.init(users, roles));

combineLatest([this.filter$, this.sort$]).pipe(
  map(([f, s]) => this.apply(f, s))
).subscribe();

660. How do withLatestFrom, scan, and bufferTime support stateful stream processing?

withLatestFrom pulls the latest value from a secondary stream; scan accumulates state across emissions like reduce; bufferTime collects emissions into arrays over fixed time windows for batch processing.

this.clicks$.pipe(
  withLatestFrom(this.user$),
  scan((acc, [click, user]) => acc + 1, 0),
  bufferTime(1000)
).subscribe(batch => this.processBatch(batch));

661. Provider scope in Angular DI

Where is a service provided when you add providedIn: 'root', and how does that differ from providing it in a component's providers array? Explain the instance lifetime and tree-shakability implications.

662. Injecting with InjectionToken

Why would you use an InjectionToken<T> instead of a class for dependency injection? Provide an example of providing a configuration object via a token and injecting it into a service.

663. Dynamic component creation

Using ViewContainerRef.createComponent(), how do you dynamically render a component at runtime? Show the minimal code to create a component, pass an input, and listen to an output.

664. Custom attribute directive

Write an attribute directive that changes the background color of its host element on mouse enter/leave using @HostListener and @HostBinding. Explain how the directive is applied in a template.

665. Pure vs impure pipes

What is the difference between a pure and an impure pipe in Angular? When would marking a pipe as pure: false be justified, and what performance cost does it introduce?

666. OnPush change detection

How does ChangeDetectionStrategy.OnPush affect when a component is checked? List the conditions that trigger re-rendering for an OnPush component and explain why mutating an @Input() object in place may not update the view.

667. Host bindings and styling

Explain how @HostBinding can be used to bind classes, styles, and attributes to a host element. Provide an example that toggles a CSS class based on a component property.

668. Content projection with ng-content

What is content projection, and how do multi-slot projection with <ng-content select=\"...\"> and fallback content work? Describe a scenario where you project content into a card component.

669. Component communication patterns

Compare @Input()/@Output() with a shared service using Subject for sibling component communication. When is each approach preferable, and what pitfalls arise with shared state?

670. Dynamic component inputs/outputs wiring

When dynamically creating a component, how do you wire inputs and outputs using the component instance reference (e.g., componentRef.instance)? Discuss change detection and destruction cleanup considerations.

671. How do you define a functional route guard in modern Angular that protects a route and redirects unauthenticated users to /login?

// auth.guard.ts
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { AuthService } from './auth.service';

export const authGuard: CanActivateFn = () => {
  const auth = inject(AuthService);
  const router = inject(Router);
  if (auth.isAuthenticated()) return true;
  return router.createUrlTree(['/login']);
};

Register it in routes with canActivate: [authGuard]. Functional guards replace class-based guards and use inject() for dependencies.

672. How can you create a functional resolver that fetches data before a route activates and passes it via route data?

import { inject } from '@angular/core';
import { ResolveFn } from '@angular/router';
import { UserService } from './user.service';
import { User } from './user.model';

export const userResolver: ResolveFn<User> = (route) => {
  const userService = inject(UserService);
  const id = route.paramMap.get('id')!;
  return userService.getById(id);
};

Attach with resolve: { user: userResolver } and read via route.data['user'] or ActivatedRoute.data.

673. Write a functional HTTP interceptor that injects a Bearer token from an AuthService, skipping auth for the login endpoint.

import { HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
import { AuthService } from './auth.service';

export const authInterceptor: HttpInterceptorFn = (req, next) => {
  const auth = inject(AuthService);
  if (req.url.endsWith('/login')) return next(req);
  const token = auth.token();
  if (!token) return next(req);
  return next(req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }));
};

Register with provideHttpClient(withInterceptors([authInterceptor])).

674. How do you implement a refresh-token flow inside an HTTP interceptor that retries the original failed request?

import { HttpInterceptorFn, HttpRequest } from '@angular/common/http';
import { inject } from '@angular/core';
import { AuthService } from './auth.service';
import { catchError, switchMap, throwError } from 'rxjs';

export const refreshInterceptor: HttpInterceptorFn = (req, next) => {
  const auth = inject(AuthService);
  return next(req).pipe(
    catchError(err => {
      if (err.status !== 401 || req.url.endsWith('/refresh')) return throwError(() => err);
      return auth.refreshToken().pipe(
        switchMap(token => {
          const retry = req.clone({ setHeaders: { Authorization: `Bearer ${token}` } });
          return next(retry);
        }),
        catchError(refreshErr => {
          auth.logout();
          return throwError(() => refreshErr);
        })
      );
    })
  );
};

Guard against infinite loops by excluding the refresh endpoint and handling concurrent 401s with a shared observable.

675. How do you provide a global error handler in Angular that logs errors and shows a toast notification?

import { ErrorHandler, Injectable, inject } from '@angular/core';
import { ToastService } from './toast.service';

@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
  private toast = inject(ToastService);
  handleError(error: unknown): void {
    console.error(error);
    this.toast.show('Something went wrong');
  }
}

// app.config.ts
export const appConfig = {
  providers: [{ provide: ErrorHandler, useClass: GlobalErrorHandler }]
};

Angular calls handleError for uncaught exceptions; keep it lightweight and avoid throwing inside it.

676. How do you create and update a writable signal immutably when adding an item to a list?

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

interface Item { id: number; name: string; }
const items = signal<Item[]>([]);

function addItem(item: Item) {
  items.update(list => [...list, item]); // immutable update
  // items.mutate(list => list.push(item)); // avoid: mutates in place
}

Use set or update with new references so change detection and computed dependents react correctly.

677. How do you derive a filtered list with a computed signal that reacts to a search term?

import { signal, computed } from '@angular/core';

const items = signal<string[]>(['apple', 'banana', 'cherry']);
const term = signal('');
const filtered = computed(() =>
  items().filter(i => i.toLowerCase().includes(term().toLowerCase()))
);

computed is memoized and only recomputes when its tracked signals change; reading filtered() returns the cached value otherwise.

678. How do you use effect with onCleanup to persist a signal to localStorage and clean up a subscription?

import { effect, signal } from '@angular/core';

const theme = signal(localStorage.getItem('theme') ?? 'light');

effect((onCleanup) => {
  localStorage.setItem('theme', theme());
  const handler = (e: StorageEvent) => {
    if (e.key === 'theme' && e.newValue) theme.set(e.newValue);
  };
  window.addEventListener('storage', handler);
  onCleanup(() => window.removeEventListener('storage', handler));
});

onCleanup runs before the next effect execution and when the owning context is destroyed.

679. How do you test a component that depends on an async service using TestBed and HttpClientTesting?

import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { provideHttpClientTesting, HttpTestingController } from '@angular/common/http/testing';

beforeEach(() => {
  TestBed.configureTestingModule({
    imports: [UserComponent],
    providers: [provideHttpClient(), provideHttpClientTesting()]
  });
  httpMock = TestBed.inject(HttpTestingController);
});

it('loads user', () => {
  const fixture = TestBed.createComponent(UserComponent);
  fixture.detectChanges();
  const req = httpMock.expectOne('/api/user/1');
  req.flush({ id: 1, name: 'Ada' });
  fixture.detectChanges();
  expect(fixture.nativeElement.textContent).toContain('Ada');
  httpMock.verify();
});

Use fixture.whenStable() or waitForAsync when assertions depend on microtask/macrotask completion.

680. How do you write an RxJS marble test for a debounced search observable?

import { TestScheduler } from 'rxjs/testing';
import { debounceTime, map } from 'rxjs/operators';

const scheduler = new TestScheduler((a, b) => expect(a).toEqual(b));

it('debounces input', () => {
  scheduler.run(({ cold, expectObservable }) => {
    const source = cold('a 99ms b 99ms c|', { a: 'x', b: 'xy', c: 'xyz' });
    const result = source.pipe(debounceTime(100, scheduler), map(v => v.toUpperCase()));
    expectObservable(result).toBe('199ms c|', { c: 'XYZ' });
  });
});

Use TestScheduler with virtual time; pass the scheduler to time-based operators so delays are deterministic.

Advanced 426 questions

Custom decorators, guards and interceptors in depth, performance, architecture and the production hardening of a large Angular application. Original page

681. How do you create a custom Angular decorator?

To create a custom decorator in Angular, you define a function that returns a function which is applied to the target. For example:

function LogClass(target: Function) {
    console.log("Class:", target);
}

@LogClass
class ExampleClass {}
            

682. What are Angular Guards and how do you implement them?

Angular Guards are interfaces that allow you to control access to routes. They are implemented by creating classes that implement one or more of the guard interfaces:

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

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(private router: Router) {}

  canActivate(): boolean {
    const isLoggedIn = /* logic to check if the user is logged in */;
    if (isLoggedIn) {
      return true;
    } else {
      this.router.navigate(['/login']);
      return false;
    }
  }
}
            

683. How can you create a dynamic form in Angular?

You can create dynamic forms using FormBuilder and FormGroup. Here's an example:

import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-dynamic-form',
  template: \`
    <form [formGroup]="form">
      <label for="name">Name:</label>
      <input id="name" formControlName="name">
      <label for="age">Age:</label>
      <input id="age" formControlName="age">
    </form>
  \`
})
export class DynamicFormComponent {
  form: FormGroup;

  constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
      name: [''],
      age: ['']
    });
  }
}
            

684. Explain how Angular's Change Detection Strategy works.

Angular's default change detection strategy is CheckAlways, where Angular checks all components to see if they need to be updated. You can use the OnPush strategy to optimize performance, which only checks the component when its inputs change or when an event occurs:

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

@Component({
  selector: 'app-on-push',
  templateUrl: './on-push.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class OnPushComponent {
  // Component logic
}
            

685. How do you manage state in Angular applications?

State management in Angular can be handled using libraries like NgRx or Akita. For example, using NgRx involves creating actions, reducers, and selectors:

import { createAction, props } from '@ngrx/store';

export const loadItems = createAction('[Items Page] Load Items');
export const loadItemsSuccess = createAction('[Items API] Items Loaded Success', props<{ items: any[] }>());

import { createReducer, on } from '@ngrx/store';

export const initialState = [];

const _itemsReducer = createReducer(
  initialState,
  on(loadItemsSuccess, (state, { items }) => [...items])
);

export function itemsReducer(state, action) {
  return _itemsReducer(state, action);
}
            

686. What is Angular's Dependency Injection system and how do you use it?

Dependency Injection (DI) in Angular allows you to inject dependencies (services) into components and other services. You can use it by defining a service and then injecting it into a component:

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

@Injectable({
  providedIn: 'root'
})
export class MyService {
  // Service logic
}

import { Component } from '@angular/core';
import { MyService } from './my.service';

@Component({
  selector: 'app-example',
  template: \`<p>Example component</p>\`
})
export class ExampleComponent {
  constructor(private myService: MyService) {}
}
            

687. How do you use Angular's HttpClient to make API requests?

The HttpClient module is used to make HTTP requests. Here's an example of making a GET request:

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

@Component({
  selector: 'app-api',
  template: \`<p>Data: {{ data | json }}</p>\`
})
export class ApiComponent {
  data: any;

  constructor(private http: HttpClient) {
    this.http.get('https://api.example.com/data')
      .subscribe(response => {
        this.data = response;
      });
  }
}
            

688. How can you optimize Angular application performance?

Performance can be optimized using techniques such as lazy loading, trackBy in ngFor, and OnPush change detection strategy:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

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

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

<ng-container *ngFor="let item of items; trackBy: trackById">
  <div>{{ item.name }}</div>
</ng-container>

trackById(index: number, item: any): number {
  return item.id;
}
            

689. Explain Angular's Reactive Forms and their advantages.

Reactive Forms provide a model-driven approach to handle form inputs. They offer advantages like better scalability, easier unit testing, and more control over form validation:

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

@Component({
  selector: 'app-reactive-form',
  template: \`
    <form [formGroup]="form" (ngSubmit)="onSubmit()">
      <input formControlName="name">
      <input formControlName="email">
      <button type="submit">Submit</button>
    </form>
  \`
})
export class ReactiveFormComponent {
  form: FormGroup;

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

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

690. How do you handle Angular routes with parameters?

To handle routes with parameters, define parameters in the route configuration and access them in the component:

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

@Component({
  selector: 'app-route-param',
  template: \`<p>Param: {{ id }}</p>\`
})
export class RouteParamComponent implements OnInit {
  id: string;

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.route.paramMap.subscribe(params => {
      this.id = params.get('id');
    });
  }
}
            

691. What is Angular's NgZone and how do you use it?

NgZone allows you to run code inside or outside Angular's change detection. This is useful for optimizing performance:

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

@Component({
  selector: 'app-ngzone',
  template: \`<p>NgZone example</p>\`
})
export class NgZoneComponent {
  constructor(private ngZone: NgZone) {
    this.ngZone.runOutsideAngular(() => {
      // Code that does not trigger change detection
    });
  }
}
            

692. How do you create an Angular library and use it in an application?

Create a library using Angular CLI and then include it in your application:

ng generate library my-lib
ng build my-lib

// In your application module
import { MyLibModule } from 'my-lib';

@NgModule({
  imports: [MyLibModule]
})
export class AppModule { }
            

693. How can you implement server-side rendering with Angular?

Angular Universal is used for server-side rendering (SSR). It allows rendering Angular applications on the server before sending them to the client:

ng add @nguniversal/express-engine

// server.ts
import 'zone.js/dist/zone-node';
import { ngExpressEngine } from '@nguniversal/express-engine';
import { provideModuleMap } from '@nguniversal/module-map-ngfactory-loader';
import { AppServerModule } from './src/main.server';

const app = express();
app.engine('html', ngExpressEngine({
  bootstrap: AppServerModule,
  providers: [provideModuleMap(LAZY_MODULE_MAP)]
}));
            

694. How do you create custom Angular pipes?

Custom pipes are created by implementing the PipeTransform interface:

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

@Pipe({
  name: 'customPipe'
})
export class CustomPipe implements PipeTransform {
  transform(value: string, ...args: any[]): string {
    return value.toUpperCase();
  }
}
            

695. How do you use Angular's built-in validators in forms?

Angular provides several built-in validators for forms:

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

@Component({
  selector: 'app-validators',
  template: \`
    <form [formGroup]="form">
      <input formControlName="email">
      <input formControlName="password">
    </form>
  \`
})
export class ValidatorsComponent {
  form: FormGroup;

  constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
      email: ['', [Validators.required, Validators.email]],
      password: ['', [Validators.required, Validators.minLength(6)]]
    });
  }
}
            

696. What is Angular's Content Projection and how do you use it?

Content projection allows you to pass content into a component's template. Use the <ng-content> directive:

<ng-content></ng-content>

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

@Component({
  selector: 'app-content-projection',
  template: \`
    <div>
      <ng-content></ng-content>
    </div>
  \`
})
export class ContentProjectionComponent {}
            

697. How do you implement Angular's Lazy Loading for feature modules?

Feature modules can be lazy-loaded by configuring routes with loadChildren:

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

698. How do you handle asynchronous data with Angular's Observables?

Observables are used to handle asynchronous data. Use the subscribe method to react to data changes:

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { DataService } from './data.service';

@Component({
  selector: 'app-observable',
  template: \`<p>Data: {{ data | json }}</p>\`
})
export class ObservableComponent implements OnInit {
  data$: Observable<any>;

  constructor(private dataService: DataService) {}

  ngOnInit() {
    this.data$ = this.dataService.getData();
  }
}
            

699. What is Angular's ViewChild and how is it used?

ViewChild allows you to access a child component or element in your template:

import { Component, ViewChild } from '@angular/core';
import { ChildComponent } from './child.component';

@Component({
  selector: 'app-parent',
  template: \`<app-child #childRef></app-child>\`
})
export class ParentComponent {
  @ViewChild('childRef') childComponent: ChildComponent;

  ngAfterViewInit() {
    console.log(this.childComponent);
  }
}
            

700. How do you handle Angular's Lifecycle Hooks?

Lifecycle hooks are methods in Angular that allow you to tap into key moments of a component's lifecycle:

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

@Component({
  selector: 'app-lifecycle',
  template: \`<p>Lifecycle hooks example</p>\`
})
export class LifecycleComponent implements OnInit, OnDestroy {
  ngOnInit() {
    console.log('Component Initialized');
  }

  ngOnDestroy() {
    console.log('Component Destroyed');
  }
}
            

 

Angular Advanced Level Questions - Part 2

701. How do you implement Angular's Custom Validators?

Custom validators are used to add validation logic to form controls. Implement a custom validator by creating a function that returns either null or an object indicating the validation error:

import { AbstractControl, ValidatorFn } from '@angular/forms';

export function forbiddenNameValidator(nameRe: RegExp): ValidatorFn {
  return (control: AbstractControl): {[key: string]: any} | null => {
    const forbidden = nameRe.test(control.value);
    return forbidden ? { 'forbiddenName': { value: control.value } } : null;
  };
}

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

@Component({
  selector: 'app-custom-validator',
  template: \`
    <form [formGroup]="form">
      <input formControlName="name">
      <div *ngIf="form.get('name').hasError('forbiddenName')">
        Name is forbidden
      </div>
    </form>
  \`
})
export class CustomValidatorComponent {
  form: FormGroup;

  constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
      name: ['', [forbiddenNameValidator(/admin/)]]
    });
  }
}
            

702. How do you use Angular's Dependency Injection to provide multiple instances of a service?

To provide multiple instances of a service, use different providers with a unique token:

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

export const MY_SERVICE_TOKEN = new InjectionToken<MyService>('MyService');

@Injectable()
export class MyService {
  constructor() {}
}

@NgModule({
  providers: [
    { provide: MY_SERVICE_TOKEN, useClass: MyService }
  ]
})
export class AppModule { }
            

703. How can you handle HTTP errors globally in Angular?

Use an HTTP interceptor to catch and handle HTTP errors:

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpErrorResponse } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler) {
    return next.handle(req).pipe(
      catchError((error: HttpErrorResponse) => {
        console.error('HTTP Error:', error);
        return throwError(error);
      })
    );
  }
}
            

704. How do you use Angular's Router to handle child routes?

Define child routes within a parent route configuration:

const routes: Routes = [
  {
    path: 'parent',
    component: ParentComponent,
    children: [
      { path: 'child1', component: Child1Component },
      { path: 'child2', component: Child2Component }
    ]
  }
];
            

705. How can you manage Angular application state with NgRx Effects?

NgRx Effects allow you to handle side effects in your application. Create effects to listen for actions and perform tasks like HTTP requests:

import { Injectable } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { MyService } from './my.service';
import { loadItems, loadItemsSuccess } from './actions';
import { switchMap } from 'rxjs/operators';

@Injectable()
export class MyEffects {
  loadItems$ = createEffect(() =>
    this.actions$.pipe(
      ofType(loadItems),
      switchMap(() => this.myService.getItems()
        .pipe(map(items => loadItemsSuccess({ items })))
      )
    )
  );

  constructor(
    private actions$: Actions,
    private myService: MyService
  ) {}
}
            

706. How do you create a custom Angular Directive?

Custom directives are used to extend HTML behavior. Create a directive by defining a class and using the @Directive decorator:

import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  constructor(private el: ElementRef, private renderer: Renderer2) {}

  @HostListener('mouseenter') onMouseEnter() {
    this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow');
  }

  @HostListener('mouseleave') onMouseLeave() {
    this.renderer.removeStyle(this.el.nativeElement, 'backgroundColor');
  }
}
            

707. How can you use Angular's `ViewEncapsulation` to control CSS styles?

Angular provides different encapsulation strategies for component styles. Use ViewEncapsulation to control this:

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

@Component({
  selector: 'app-encapsulation',
  template: \`<p>Encapsulation example</p>\`,
  styles: [\`
    p {
      color: red;
    }
  \`],
  encapsulation: ViewEncapsulation.None
})
export class EncapsulationComponent {}
            

708. How do you implement lazy loading for Angular modules?

Use the loadChildren property in route configurations to lazy-load modules:

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

709. What is Angular's `ChangeDetectorRef` and how is it used?

ChangeDetectorRef provides methods to manually trigger change detection in a component:

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

@Component({
  selector: 'app-change-detection',
  template: \`<p>Change detection example</p>\`
})
export class ChangeDetectionComponent {
  constructor(private cdr: ChangeDetectorRef) {}

  detectChanges() {
    this.cdr.detectChanges();
  }
}
            

710. How can you use Angular's `Renderer2` for DOM manipulation?

Renderer2 is used to safely manipulate the DOM in Angular. Here’s an example of adding a class to an element:

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

@Component({
  selector: 'app-renderer',
  template: \`<div #myDiv>Renderer2 Example</div>\`
})
export class RendererComponent {
  constructor(private el: ElementRef, private renderer: Renderer2) {}

  ngAfterViewInit() {
    const div = this.el.nativeElement.querySelector('div');
    this.renderer.addClass(div, 'highlight');
  }
}
            

711. How do you use Angular's `AsyncPipe` for handling asynchronous data in templates?

AsyncPipe allows you to subscribe to observables directly in the template:

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { DataService } from './data.service';

@Component({
  selector: 'app-async-pipe',
  template: \`<p>Data: {{ data$ | async | json }}</p>\`
})
export class AsyncPipeComponent implements OnInit {
  data$: Observable<any>;

  constructor(private dataService: DataService) {}

  ngOnInit() {
    this.data$ = this.dataService.getData();
  }
}
            

712. How do you use Angular's `ChangeDetectionStrategy`?

ChangeDetectionStrategy controls how Angular checks for changes in a component. Use ChangeDetectionStrategy.OnPush to optimize performance:

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

@Component({
  selector: 'app-change-detection-strategy',
  template: \`<p>Change Detection Strategy Example</p>\`,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChangeDetectionStrategyComponent {}
            

713. How do you use Angular's `HostBinding` and `HostListener` decorators?

HostBinding and HostListener are used to bind properties and listen to events on the host element:

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

@Component({
  selector: 'app-host',
  template: \`<p>Host Binding and Listener Example</p>\`
})
export class HostComponent {
  @HostBinding('class.highlight') isHighlighted = true;

  @HostListener('click') onClick() {
    this.isHighlighted = !this.isHighlighted;
  }
}
            

714. How do you handle Angular's `ngOnChanges` lifecycle hook?

ngOnChanges is called when an input property value changes:

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

@Component({
  selector: 'app-on-changes',
  template: \`<p>On Changes Example</p>\`
})
export class OnChangesComponent implements OnChanges {
  @Input() data: any;

  ngOnChanges(changes: SimpleChanges) {
    console.log('Changes:', changes);
  }
}
            

715. How do you use Angular's `ng-container` and `ng-template`?

ng-container and ng-template are used to manage templates and control the rendering:

<ng-container *ngIf="condition">
  <ng-template #template>
    </ng-template></ng-container><ng-container *ngIf="condition"><ng-template #template><p>Content to render</p>
  </ng-template>
</ng-container>

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

@Component({
  selector: 'app-container',
  template: \`
    <ng-container *ngIf="showContent; else noContent">
      </ng-container><ng-container *ngIf="showContent; else noContent"><p>Content is visible</p>
    </ng-container>
    <ng-template #noContent>
      </ng-template><ng-template #noContent><p>Content is hidden</p>
    </ng-template>
  \`
})
export class ContainerComponent {
  showContent = true;
}
            

716. How do you manage Angular's environment configurations?

Manage environment configurations using environment files:

// environment.ts
export const environment = {
  production: false,
  apiUrl: 'http://localhost:3000'
};

// environment.prod.ts
export const environment = {
  production: true,
  apiUrl: 'https://api.example.com'
};
            

717. How do you create Angular's custom structural directives?

Custom structural directives are created using the *ngIf and *ngFor syntax:

import { Directive, TemplateRef, ViewContainerRef } from '@angular/core';

@Directive({
  selector: '[appMyDirective]'
})
export class MyDirective {
  constructor(private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) {}

  @Input() set appMyDirective(condition: boolean) {
    this.viewContainer.clear();
    if (condition) {
      this.viewContainer.createEmbeddedView(this.templateRef);
    }
  }
}
            

718. How can you configure Angular's global error handling?

Global error handling is configured using an error handler class:

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

@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
  handleError(error: any) {
    console.error('Global error:', error);
  }
}

@NgModule({
  providers: [{ provide: ErrorHandler, useClass: GlobalErrorHandler }]
})
export class AppModule { }
            

719. How do you implement Angular's Internationalization (i18n)?

Internationalization is handled using the Angular i18n package:

ng add @angular/localize

// app.component.html
<p i18n="@@hello">Hello</p>

// Extract messages
ng extract-i18n

// Translate and build for a specific locale
ng build --localize
            

720. How do you use Angular's `Renderer2` to create dynamic components?

Renderer2 can be used to dynamically create and manipulate components:

import { Component, ComponentFactoryResolver, ViewChild, ViewContainerRef } from '@angular/core';
import { DynamicComponent } from './dynamic.component';

@Component({
  selector: 'app-dynamic',
  template: \`<ng-template #container></ng-template>\`
})
export class DynamicComponentLoader {
  @ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef;

  constructor(private resolver: ComponentFactoryResolver) {}

  loadComponent() {
    const factory = this.resolver.resolveComponentFactory(DynamicComponent);
    this.container.clear();
    this.container.createComponent(factory);
  }
}
            

 

Angular Advanced Level Questions - Part 3

721. How do you implement Angular's Custom Pipes?

Custom pipes are used to transform data in the template. Create a pipe by defining a class and using the @Pipe decorator:

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

@Pipe({
  name: 'customPipe'
})
export class CustomPipe implements PipeTransform {
  transform(value: string, ...args: any[]): string {
    return value.toUpperCase();
  }
}
            

722. How can you use Angular's `ChangeDetectorRef` to handle manual change detection?

ChangeDetectorRef can be used to manually control change detection, such as when you need to update the view outside of Angular's default change detection cycle:

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

@Component({
  selector: 'app-manual-change',
  template: \`<p>{{ data }}</p>\`
})
export class ManualChangeComponent {
  data = 'Initial data';

  constructor(private cdr: ChangeDetectorRef) {}

  updateData() {
    this.data = 'Updated data';
    this.cdr.detectChanges();
  }
}
            

723. How do you create Angular's reactive forms with custom validators?

Reactive forms allow for more complex validation logic. Here’s how to create a form with custom validators:

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

@Component({
  selector: 'app-reactive-form',
  template: \`
    <form [formGroup]="form" (ngSubmit)="onSubmit()">
      <input formControlName="username">
      <div *ngIf="form.get('username').hasError('forbiddenName')">
        Username is forbidden
      </div>
      <button type="submit">Submit</button>
    </form>
  \`
})
export class ReactiveFormComponent {
  form: FormGroup;

  constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
      username: ['', [this.forbiddenNameValidator(/admin/)]]
    });
  }

  forbiddenNameValidator(nameRe: RegExp) {
    return (control: AbstractControl): {[key: string]: any} | null => {
      const forbidden = nameRe.test(control.value);
      return forbidden ? { 'forbiddenName': { value: control.value } } : null;
    };
  }

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

724. How do you implement Angular's Dynamic Component Loader?

Use Angular's ComponentFactoryResolver to dynamically load components:

import { Component, ComponentFactoryResolver, ViewChild, ViewContainerRef } from '@angular/core';
import { DynamicComponent } from './dynamic.component';

@Component({
  selector: 'app-dynamic-loader',
  template: \`<ng-template #container></ng-template>\`
})
export class DynamicLoaderComponent {
  @ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef;

  constructor(private resolver: ComponentFactoryResolver) {}

  loadComponent() {
    const factory = this.resolver.resolveComponentFactory(DynamicComponent);
    this.container.clear();
    this.container.createComponent(factory);
  }
}
            

725. How do you handle Angular's module lazy loading?

Lazy loading modules allows for more efficient loading of Angular applications. Define a lazy-loaded module in your routing configuration:

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

726. How do you use Angular's `NgRx` store for state management?

NgRx provides a way to manage state in Angular applications using a store. Define actions, reducers, and effects:

import { createAction, createReducer, on } from '@ngrx/store';

// Actions
export const loadItems = createAction('[Item] Load Items');
export const loadItemsSuccess = createAction('[Item] Load Items Success', (items: any[]) => ({ items }));

// Reducer
export const initialState = [];
const _itemsReducer = createReducer(
  initialState,
  on(loadItemsSuccess, (state, { items }) => [...items])
);

export function itemsReducer(state, action) {
  return _itemsReducer(state, action);
}
            

727. How do you create Angular's custom structural directives?

Structural directives change the structure of the DOM. Create a custom structural directive like this:

import { Directive, TemplateRef, ViewContainerRef, Input } from '@angular/core';

@Directive({
  selector: '[appUnless]'
})
export class UnlessDirective {
  constructor(private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) {}

  @Input() set appUnless(condition: boolean) {
    if (!condition) {
      this.viewContainer.createEmbeddedView(this.templateRef);
    } else {
      this.viewContainer.clear();
    }
  }
}
            

728. How can you use Angular's `HostListener` to listen to DOM events?

HostListener can be used to listen to events on the host element of a component:

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

@Component({
  selector: 'app-host-listener',
  template: \`<p>Host Listener Example</p>\`
})
export class HostListenerComponent {
  @HostListener('click', ['$event'])
  onClick(event: Event) {
    console.log('Host element clicked:', event);
  }
}
            

729. How do you use Angular's `ng-content` for content projection?

ng-content allows you to project content into a component:

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

@Component({
  selector: 'app-content',
  template: \`<ng-content></ng-content>\`
})
export class ContentComponent {}
            

730. How can you use Angular's `@ContentChild` and `@ContentChildren` decorators?

@ContentChild and @ContentChildren are used to access content projected into a component:

import { Component, ContentChild, ContentChildren, QueryList } from '@angular/core';

@Component({
  selector: 'app-content-query',
  template: \`<ng-content></ng-content>\`
})
export class ContentQueryComponent {
  @ContentChild('contentRef') contentChild: ElementRef;
  @ContentChildren('contentRef') contentChildren: QueryList<ElementRef>;
}
            

731. How do you create Angular's custom decorators?

Custom decorators can be used to add metadata to classes or methods:

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

export function CustomDecorator(message: string) {
  return createDecorator((target: Function) => {
    target.prototype.customMessage = message;
  });
}

@CustomDecorator('Hello World')
export class CustomClass {
  customMessage: string;
}
            

732. How can you use Angular's Dependency Injection for service scoping?

Dependency injection scopes can be controlled using the providedIn property:

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

@Injectable({
  providedIn: 'root'  // Singleton scope
})
export class MyService {}

@Injectable({
  providedIn: 'any'   // Scoped to any module or component
})
export class ScopedService {}
            

733. How do you manage Angular's HTTP interceptor for request/response handling?

HTTP interceptors can be used to modify requests and responses globally:

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const authReq = req.clone({
      headers: req.headers.set('Authorization', 'Bearer my-token')
    });
    return next.handle(authReq);
  }
}
            

734. How do you handle Angular's Router Guards for route protection?

Router guards can be used to protect routes based on conditions:

import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(private router: Router) {}

  canActivate(): Observable<boolean> | Promise<boolean> | boolean {
    const isAuthenticated = false;  // Implement your authentication check here
    if (!isAuthenticated) {
      this.router.navigate(['/login']);
      return false;
    }
    return true;
  }
}
            

735. How do you use Angular's `NgModule` to organize and manage your application?

NgModule helps in organizing an application into cohesive blocks of functionality:

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

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

736. How do you create Angular's custom validators for forms?

Custom validators can be created and used in reactive forms:

import { AbstractControl, ValidatorFn } from '@angular/forms';

export function passwordMatchValidator(): ValidatorFn {
  return (control: AbstractControl): {[key: string]: any} | null => {
    const password = control.get('password');
    const confirmPassword = control.get('confirmPassword');
    return password && confirmPassword && password.value !== confirmPassword.value
      ? { 'mismatch': true }
      : null;
  };
}
            

737. How do you use Angular's `@ViewChild` and `@ViewChildren` decorators?

@ViewChild and @ViewChildren are used to query and access elements or directives in the component's view:

import { Component, ViewChild, ViewChildren, QueryList } from '@angular/core';
import { ChildComponent } from './child.component';

@Component({
  selector: 'app-parent',
  template: \`
    <app-child #child></app-child>
    <app-child *ngFor="let child of children" #children></app-child>
  \`
})
export class ParentComponent {
  @ViewChild('child') child: ChildComponent;
  @ViewChildren('children') children: QueryList<ChildComponent>;
}
            

738. How do you handle Angular's lazy loading with route parameters?

Lazy loading modules with route parameters involves passing parameters to the route and configuring the module accordingly:

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

739. How can you use Angular's `Renderer2` for DOM manipulation?

Renderer2 is used for safe and compatible DOM manipulation:

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

@Component({
  selector: 'app-renderer',
  template: \`<div #box>Content</div>\`
})
export class RendererComponent {
  constructor(private renderer: Renderer2, private el: ElementRef) {}

  changeColor() {
    this.renderer.setStyle(this.el.nativeElement.querySelector('div'), 'color', 'red');
  }
}
            

740. How do you implement Angular's `ngOnInit` and `ngAfterViewInit` lifecycle hooks?

ngOnInit is called after the component is initialized, while ngAfterViewInit is called after the view has been fully initialized:

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

@Component({
  selector: 'app-lifecycle',
  template: \`<p>Lifecycle Hooks Example</p>\`
})
export class LifecycleComponent implements OnInit, AfterViewInit {
  ngOnInit() {
    console.log('OnInit called');
  }

  ngAfterViewInit() {
    console.log('AfterViewInit called');
  }
}
            

 

Angular Advanced Level Questions - Part 4

741. How do you use Angular's `NgModule` for feature modules?

Feature modules help to organize an Angular application into cohesive blocks. Here's how to set up a feature module:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FeatureComponent } from './feature.component';
import { FeatureRoutingModule } from './feature-routing.module';

@NgModule({
  declarations: [FeatureComponent],
  imports: [
    CommonModule,
    FeatureRoutingModule
  ]
})
export class FeatureModule { }
            

742. How do you create a custom Angular Directive?

Custom directives are used to extend the behavior of elements. Here’s an example of a custom directive:

import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  constructor(private el: ElementRef, private renderer: Renderer2) {}

  @HostListener('mouseenter') onMouseEnter() {
    this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow');
  }

  @HostListener('mouseleave') onMouseLeave() {
    this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'transparent');
  }
}
            

743. How do you handle Angular's Dependency Injection for multiple providers?

When you need to provide multiple instances or configurations of a service, you can use multi-provider tokens:

import { InjectionToken, Injectable, Inject } from '@angular/core';

export const CONFIG = new InjectionToken('app.config');

@Injectable({
  providedIn: 'root'
})
export class ConfigService {
  constructor(@Inject(CONFIG) private config: string[]) {}
}

// In a module
@NgModule({
  providers: [
    { provide: CONFIG, useValue: ['config1', 'config2'], multi: true }
  ]
})
export class AppModule { }
            

744. How do you optimize Angular applications for performance?

To optimize performance, you can use techniques like lazy loading, Ahead-of-Time (AOT) compilation, and change detection strategies:

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

@Component({
  selector: 'app-performance',
  templateUrl: './performance.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class PerformanceComponent {}
            

745. How do you handle Angular's dynamic forms?

Dynamic forms are built based on data received at runtime. Use Angular’s reactive forms to create dynamic controls:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';

@Component({
  selector: 'app-dynamic-form',
  template: \`
    <form [formGroup]="form">
      <div formArrayName="items">
        <div *ngFor="let item of items.controls; let i = index">
          <input [formControlName]="i">
        </div>
      </div>
    </form>
  \`
})
export class DynamicFormComponent implements OnInit {
  form: FormGroup;

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.form = this.fb.group({
      items: this.fb.array([this.fb.control('')])
    });
  }

  get items() {
    return this.form.get('items') as FormArray;
  }

  addItem() {
    this.items.push(this.fb.control(''));
  }
}
            

746. How do you implement Angular's lazy loading with nested routes?

Lazy load a module with nested routes by defining child routes in the lazy-loaded module:

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

747. How do you use Angular's `NgZone` for running code outside Angular's zone?

NgZone helps to execute code outside Angular's change detection:

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

@Component({
  selector: 'app-ngzone',
  template: \`<p>NgZone Example</p>\`
})
export class NgZoneComponent {
  constructor(private ngZone: NgZone) {
    this.ngZone.runOutsideAngular(() => {
      // Code running outside Angular's zone
    });
  }
}
            

748. How do you handle Angular's server-side rendering (SSR) with Angular Universal?

Angular Universal allows you to perform server-side rendering to improve performance and SEO. Install Angular Universal and configure it:

ng add @nguniversal/express-engine
// Configure server.ts and other settings
            

749. How do you use Angular's `Router` to handle route parameters and query parameters?

Handle route and query parameters in Angular components:

import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-route',
  template: \`<p>Route Parameter: {{ param }}</p>\`
})
export class RouteComponent implements OnInit {
  param: string;

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.route.paramMap.subscribe(params => {
      this.param = params.get('id');
    });

    this.route.queryParams.subscribe(queryParams => {
      console.log(queryParams);
    });
  }
}
            

750. How do you create and manage Angular's custom elements?

Create custom elements with Angular and use them in other applications:

import { Component, NgModule } from '@angular/core';
import { createCustomElement } from '@angular/elements';
import { BrowserModule } from '@angular/platform-browser';
import { Injector } from '@angular/core';

@Component({
  selector: 'app-custom-element',
  template: \`<p>Custom Element</p>\`
})
export class CustomElementComponent {}

@NgModule({
  declarations: [CustomElementComponent],
  imports: [BrowserModule],
  entryComponents: [CustomElementComponent]
})
export class AppModule {
  constructor(private injector: Injector) {
    const el = createCustomElement(CustomElementComponent, { injector });
    customElements.define('custom-element', el);
  }

  ngDoBootstrap() {}
}
            

751. How do you handle Angular's `HttpClient` for advanced HTTP operations?

Use HttpClient for advanced HTTP operations like interceptors, retries, and request caching:

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { catchError, retry } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class ApiService {
  constructor(private http: HttpClient) {}

  getData() {
    return this.http.get('https://api.example.com/data', {
      headers: new HttpHeaders({
        'Authorization': 'Bearer my-token'
      })
    }).pipe(
      retry(3),
      catchError(this.handleError)
    );
  }

  private handleError(error: any) {
    console.error('An error occurred', error);
    return throwError(error);
  }
}
            

752. How do you manage Angular's internationalization (i18n) and localization?

Internationalization and localization involve translating your application into different languages:

ng add @angular/localize
// Use i18n attributes in templates
// Configure locales and translations
            

753. How do you use Angular's `Renderer2` to safely manipulate the DOM?

Renderer2 provides a way to safely interact with the DOM:

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

@Component({
  selector: 'app-renderer2',
  template: \`<p>Renderer2 Example</p>\`
})
export class Renderer2Component {
  constructor(private renderer: Renderer2, private el: ElementRef) {
    this.renderer.setStyle(this.el.nativeElement, 'color', 'blue');
  }
}
            

754. How do you handle Angular's animations with the Angular Animations library?

Use Angular's Animation API to create complex animations:

import { trigger, transition, style, animate } from '@angular/animations';

@Component({
  selector: 'app-animation',
  template: \`<div [@fadeInOut]="state">Content</div>\`,
  animations: [
    trigger('fadeInOut', [
      transition(':enter', [
        style({ opacity: 0 }),
        animate('1s', style({ opacity: 1 }))
      ]),
      transition(':leave', [
        animate('1s', style({ opacity: 0 }))
      ])
    ])
  ]
})
export class AnimationComponent {
  state = 'in';
}
            

755. How do you manage Angular's change detection strategy for performance optimization?

Optimize performance by using ChangeDetectionStrategy.OnPush:

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

@Component({
  selector: 'app-optimization',
  template: \`<p>Optimization Example</p>\`,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class OptimizationComponent {}
            

756. How do you implement Angular's `@ContentChild` and `@ContentChildren` decorators?

Use @ContentChild and @ContentChildren to query and access projected content:

import { Component, ContentChild, ContentChildren, QueryList } from '@angular/core';
import { ContentComponent } from './content.component';

@Component({
  selector: 'app-parent',
  template: \`<ng-content></ng-content>\`
})
export class ParentComponent {
  @ContentChild(ContentComponent) content: ContentComponent;
  @ContentChildren(ContentComponent) contentChildren: QueryList<ContentComponent>;
}
            

757. How do you use Angular's `@HostListener` and `@HostBinding` decorators?

Use @HostListener to listen to events on the host element and @HostBinding to bind properties:

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

@Component({
  selector: 'app-host',
  template: \`<p>Host Binding and Listener Example</p>\`
})
export class HostComponent {
  @HostBinding('class.active') isActive = true;

  @HostListener('click') onClick() {
    this.isActive = !this.isActive;
  }
}
            

758. How do you use Angular's `NgModel` with two-way data binding?

NgModel enables two-way data binding in Angular forms:

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

@Component({
  selector: 'app-model',
  template: \`
    <input [(ngModel)]="value">
    <p>Value: {{ value }}</p>
  \`
})
export class ModelComponent {
  value = '';
}
            

759. How do you configure Angular's HTTP client for handling global error handling?

Global error handling can be configured with HTTP interceptors:

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).pipe(
      catchError(error => {
        console.error('An error occurred', error);
        return throwError(error);
      })
    );
  }
}
            

760. How do you implement Angular's service worker for Progressive Web Apps (PWA)?

Set up a service worker to enable PWA features:

ng add @angular/pwa
// Configure ngsw-config.json for caching strategies
            

 

Angular Advanced Level Questions - Part 5

761. How do you implement Angular's dynamic component loading?

Dynamic component loading allows you to load components at runtime. Use ComponentFactoryResolver:

import { Component, ComponentFactoryResolver, ViewChild, ViewContainerRef } from '@angular/core';
import { DynamicComponent } from './dynamic.component';

@Component({
  selector: 'app-dynamic-loader',
  template: \`<ng-template #container></ng-template>\`
})
export class DynamicLoaderComponent {
  @ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef;

  constructor(private cfr: ComponentFactoryResolver) {}

  loadComponent() {
    const factory = this.cfr.resolveComponentFactory(DynamicComponent);
    this.container.createComponent(factory);
  }
}
            

762. How do you use Angular's `@Inject` and `@Optional` decorators?

@Inject is used for dependency injection with tokens, while @Optional allows you to handle missing dependencies:

import { Injectable, Inject, Optional } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class MyService {
  constructor(@Inject('TOKEN') @Optional() private token: string) {
    if (!token) {
      console.log('No token provided');
    }
  }
}
            

763. How do you use Angular's `@ViewChild` with `static` and `dynamic` options?

@ViewChild with static or dynamic allows you to control when the view query is resolved:

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

@Component({
  selector: 'app-viewchild',
  template: \`<p #paragraph>Text</p>\`
})
export class ViewChildComponent implements AfterViewInit {
  @ViewChild('paragraph', { static: true }) paragraph;

  ngAfterViewInit() {
    console.log(this.paragraph.nativeElement.textContent);
  }
}
            

764. How do you implement Angular's state management with NgRx?

NgRx provides a way to manage state in Angular applications using Redux principles. Set up actions, reducers, and effects:

import { createAction, props } from '@ngrx/store';

export const loadItems = createAction('[Items Page] Load Items');
export const loadItemsSuccess = createAction('[Items API] Load Items Success', props<{ items: any[] }>());
export const loadItemsFailure = createAction('[Items API] Load Items Failure', props<{ error: any }>());
            

765. How do you use Angular's `@NgModule` for lazy loading and route configuration?

Configure lazy-loaded modules in your app's routing module:

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

766. How do you implement Angular's reactive form validation with custom validators?

Create custom validators for reactive forms:

import { AbstractControl, ValidatorFn } from '@angular/forms';

export function forbiddenNameValidator(nameRe: RegExp): ValidatorFn {
  return (control: AbstractControl): { [key: string]: any } | null => {
    const forbidden = nameRe.test(control.value);
    return forbidden ? { 'forbiddenName': { value: control.value } } : null;
  };
}

// Usage in a form
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-custom-validation',
  template: \`
    <form [formGroup]="form">
      <input formControlName="name">
      <div *ngIf="form.controls.name.errors?.forbiddenName">
        Name is forbidden
      </div>
    </form>
  \`
})
export class CustomValidationComponent {
  form: FormGroup;

  constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
      name: ['', [forbiddenNameValidator(/admin/)]]
    });
  }
}
            

767. How do you use Angular's `@ContentChildren` to query multiple elements?

Use @ContentChildren to query multiple projected elements:

import { Component, ContentChildren, QueryList, AfterContentInit } from '@angular/core';
import { ContentComponent } from './content.component';

@Component({
  selector: 'app-parent',
  template: \`<ng-content></ng-content>\`
})
export class ParentComponent implements AfterContentInit {
  @ContentChildren(ContentComponent) contentComponents: QueryList<ContentComponent>;

  ngAfterContentInit() {
    this.contentComponents.forEach(component => {
      console.log(component.someProperty);
    });
  }
}
            

768. How do you handle Angular's router guards for authorization?

Router guards help manage navigation based on conditions like authentication:

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

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(private router: Router) {}

  canActivate(): boolean {
    const isAuthenticated = false; // Replace with real authentication check
    if (!isAuthenticated) {
      this.router.navigate(['/login']);
    }
    return isAuthenticated;
  }
}
            

769. How do you use Angular's `@ViewEncapsulation` to control component styles?

Control component styles encapsulation with @ViewEncapsulation:

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

@Component({
  selector: 'app-encapsulation',
  template: \`<p>Encapsulation Example</p>\`,
  styles: [\`
    p {
      color: red;
    }
  \`],
  encapsulation: ViewEncapsulation.None
})
export class EncapsulationComponent {}
            

770. How do you implement Angular's `@HostListener` to listen to events on the host element?

Use @HostListener to listen to events like click or hover:

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

@Component({
  selector: 'app-host-listener',
  template: \`<p>Host Listener Example</p>\`
})
export class HostListenerComponent {
  @HostListener('click', ['$event'])
  onClick(event: Event) {
    console.log('Element clicked', event);
  }
}
            

771. How do you use Angular's `@HostBinding` to bind properties to the host element?

@HostBinding allows you to bind properties like classes or styles:

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

@Component({
  selector: 'app-host-binding',
  template: \`<p>Host Binding Example</p>\`
})
export class HostBindingComponent {
  @HostBinding('class.active') isActive = true;
}
            

772. How do you implement Angular's `@Injectable` with hierarchical injectors?

Use @Injectable with providedIn to control hierarchical injection:

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

@Injectable({
  providedIn: 'root' // Hierarchical injectors are created with this configuration
})
export class MyService {}
            

773. How do you use Angular's dependency injection with factory providers?

Factory providers allow custom instantiation of services:

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

export function myServiceFactory() {
  return new MyService();
}

@NgModule({
  providers: [
    { provide: MyService, useFactory: myServiceFactory }
  ]
})
export class AppModule {}
            

774. How do you use Angular's `@Inject` to inject values in services?

Inject values using tokens and @Inject:

import { Injectable, InjectionToken, Inject } from '@angular/core';

export const MY_TOKEN = new InjectionToken<string>('MyToken');

@Injectable({
  providedIn: 'root'
})
export class MyService {
  constructor(@Inject(MY_TOKEN) private token: string) {}
}
            

775. How do you implement Angular's HTTP client with interceptors for authentication?

Use HTTP interceptors to modify requests and responses:

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const authReq = req.clone({
      headers: req.headers.set('Authorization', 'Bearer token')
    });
    return next.handle(authReq);
  }
}
            

776. How do you use Angular's `@NgModule` to configure application-wide services?

Configure application-wide services in @NgModule:

import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { MyService } from './my.service';

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

777. How do you implement Angular's `@ViewChild` to access child components?

Access child components with @ViewChild:

import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { ChildComponent } from './child.component';

@Component({
  selector: 'app-parent',
  template: \`<app-child></app-child>\`
})
export class ParentComponent implements AfterViewInit {
  @ViewChild(ChildComponent) childComponent: ChildComponent;

  ngAfterViewInit() {
    console.log(this.childComponent.someMethod());
  }
}
            

778. How do you implement Angular's `ChangeDetectorRef` for manual change detection?

Use ChangeDetectorRef for manual change detection:

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

@Component({
  selector: 'app-manual-detection',
  template: \`<p>Manual Detection Example</p>\`
})
export class ManualDetectionComponent {
  constructor(private cdr: ChangeDetectorRef) {}

  triggerChangeDetection() {
    this.cdr.detectChanges();
  }
}
            

779. How do you use Angular's `@NgModule` to define feature modules and lazy loading?

Define feature modules and configure lazy loading in @NgModule:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

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

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

780. How do you use Angular's `@Injectable` for hierarchical dependency injection?

Manage hierarchical dependencies with @Injectable:

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

@Injectable({
  providedIn: 'root' // or 'platform' or 'any'
})
export class MyService {}
            

 

Angular Advanced Level Questions - Part 6

781. How do you use Angular's `@Directive` to create custom directives?

Define custom directives to extend HTML behavior:

import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  constructor(private el: ElementRef, private renderer: Renderer2) {}

  @HostListener('mouseenter') onMouseEnter() {
    this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow');
  }

  @HostListener('mouseleave') onMouseLeave() {
    this.renderer.removeStyle(this.el.nativeElement, 'backgroundColor');
  }
}
            

782. How do you implement Angular's custom pipes?

Create custom pipes to transform data in templates:

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

@Pipe({
  name: 'reverse'
})
export class ReversePipe implements PipeTransform {
  transform(value: string): string {
    return value.split('').reverse().join('');
  }
}
            

783. How do you handle Angular's `@Input` and `@Output` for parent-child communication?

Use @Input to pass data from parent to child, and @Output to emit events from child to parent:

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

@Component({
  selector: 'app-child',
  template: \`<button (click)="notify()">Notify Parent</button>\`
})
export class ChildComponent {
  @Input() data: string;
  @Output() notify = new EventEmitter<string>();

  notifyParent() {
    this.notify.emit('Message from child');
  }
}

@Component({
  selector: 'app-parent',
  template: \`<app-child [data]="parentData" (notify)="onNotify($event)"></app-child>\`
})
export class ParentComponent {
  parentData = 'Data from parent';

  onNotify(message: string) {
    console.log(message);
  }
}
            

784. How do you use Angular's `@NgModule` to configure lazy-loaded modules and route guards?

Configure lazy-loaded modules and route guards in your routing module:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AuthGuard } from './auth.guard';

const routes: Routes = [
  {
    path: 'admin',
    loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule),
    canActivate: [AuthGuard]
  }
];

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

785. How do you use Angular's `@NgModule` to configure providers for dependency injection?

Provide services at different levels using @NgModule:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MyService } from './my.service';

@NgModule({
  imports: [CommonModule],
  providers: [MyService]
})
export class FeatureModule {}
            

786. How do you use Angular's `@HostListener` to listen for DOM events on the host element?

Listen to DOM events using @HostListener:

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

@Component({
  selector: 'app-host-listener',
  template: \`<p>Click me!</p>\`
})
export class HostListenerComponent {
  @HostListener('click', ['$event'])
  onClick(event: Event) {
    console.log('Element clicked:', event);
  }
}
            

787. How do you implement Angular's `@ContentChild` and `@ContentChildren` to query content projected into a component?

Use @ContentChild and @ContentChildren to query projected content:

import { Component, ContentChild, ContentChildren, QueryList, AfterContentInit } from '@angular/core';
import { ContentComponent } from './content.component';

@Component({
  selector: 'app-container',
  template: \`<ng-content></ng-content>\`
})
export class ContainerComponent implements AfterContentInit {
  @ContentChild(ContentComponent) contentChild: ContentComponent;
  @ContentChildren(ContentComponent) contentChildren: QueryList<ContentComponent>;

  ngAfterContentInit() {
    console.log(this.contentChild);
    this.contentChildren.forEach(child => console.log(child));
  }
}
            

788. How do you handle Angular's dynamic component loading with `ComponentFactoryResolver`?

Load components dynamically using ComponentFactoryResolver:

import { Component, ComponentFactoryResolver, ViewChild, ViewContainerRef } from '@angular/core';
import { DynamicComponent } from './dynamic.component';

@Component({
  selector: 'app-dynamic',
  template: \`<ng-template #container></ng-template>\`
})
export class DynamicComponentLoader {
  @ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef;

  constructor(private cfr: ComponentFactoryResolver) {}

  loadComponent() {
    const factory = this.cfr.resolveComponentFactory(DynamicComponent);
    this.container.createComponent(factory);
  }
}
            

789. How do you use Angular's `ChangeDetectionStrategy` for performance optimization?

Optimize performance using ChangeDetectionStrategy.OnPush:

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

@Component({
  selector: 'app-optimization',
  template: \`<p>Change Detection Strategy</p>\`,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class OptimizationComponent {}
            

790. How do you use Angular's `NgZone` for controlling change detection?

Control change detection with NgZone:

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

@Component({
  selector: 'app-ngzone',
  template: \`<p>NgZone Example</p>\`
})
export class NgZoneComponent {
  constructor(private ngZone: NgZone) {
    this.ngZone.runOutsideAngular(() => {
      setTimeout(() => {
        this.ngZone.run(() => console.log('Change detection triggered'));
      }, 1000);
    });
  }
}
            

791. How do you use Angular's `HttpClient` for making HTTP requests and handling responses?

Make HTTP requests using HttpClient:

import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-http',
  template: \`<p>HTTP Request Example</p>\`
})
export class HttpComponent {
  constructor(private http: HttpClient) {}

  getData(): Observable<any> {
    return this.http.get('https://api.example.com/data');
  }
}
            

792. How do you use Angular's `@Injectable` to provide services at different levels of the injector hierarchy?

Define service providers at different levels:

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

@Injectable({
  providedIn: 'root' // Service provided at the root level
})
export class MyService {}
            

793. How do you use Angular's `NgModule` to configure providers for third-party libraries?

Configure third-party library providers in @NgModule:

import { NgModule } from '@angular/core';
import { SomeLibraryModule, SomeService } from 'some-library';

@NgModule({
  imports: [SomeLibraryModule],
  providers: [SomeService]
})
export class AppModule {}
            

794. How do you use Angular's `Router` to handle route parameters and query parameters?

Access route and query parameters using Router:

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

@Component({
  selector: 'app-route',
  template: \`<p>Route Example</p>\`
})
export class RouteComponent implements OnInit {
  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.route.paramMap.subscribe(params => {
      const id = params.get('id');
      console.log('Route parameter id:', id);
    });

    this.route.queryParamMap.subscribe(params => {
      const filter = params.get('filter');
      console.log('Query parameter filter:', filter);
    });
  }
}
            

795. How do you use Angular's `@Directive` to create structural directives?

Create structural directives to manipulate DOM layout:

import { Directive, TemplateRef, ViewContainerRef } from '@angular/core';

@Directive({
  selector: '[appUnless]'
})
export class UnlessDirective {
  constructor(private templateRef: TemplateRef<any>, private vcr: ViewContainerRef) {}

  set appUnless(condition: boolean) {
    if (!condition) {
      this.vcr.createEmbeddedView(this.templateRef);
    } else {
      this.vcr.clear();
    }
  }
}
            

796. How do you use Angular's `@Component` to manage view encapsulation?

Control view encapsulation with encapsulation property:

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

@Component({
  selector: 'app-encapsulation',
  template: \`<p>View Encapsulation Example</p>\`,
  encapsulation: ViewEncapsulation.None // or Emulated, Native
})
export class EncapsulationComponent {}

            

797. How do you use Angular's `@NgModule` to configure root and feature modules?

Define root and feature modules in your application:

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

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

798. How do you use Angular's `@NgModule` to configure providers and imports for feature modules?

Configure providers and imports in feature modules:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FeatureComponent } from './feature.component';
import { FeatureService } from './feature.service';

@NgModule({
  declarations: [FeatureComponent],
  imports: [CommonModule],
  providers: [FeatureService]
})
export class FeatureModule {}
            

799. How do you use Angular's `@Injectable` to configure hierarchical dependencies?

Manage hierarchical dependencies using @Injectable:

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

@Injectable({
  providedIn: 'root' // or 'platform', 'any'
})
export class HierarchicalService {}
            

800. How do you handle Angular's change detection with `ChangeDetectorRef` and `NgZone`?

Combine ChangeDetectorRef and NgZone to control change detection:

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

@Component({
  selector: 'app-change-detection',
  template: \`<p>Change Detection Example</p>\`
})
export class ChangeDetectionComponent {
  constructor(private cdr: ChangeDetectorRef, private ngZone: NgZone) {}

  triggerChangeDetection() {
    this.ngZone.run(() => this.cdr.detectChanges());
  }
}
            

Angular Advanced Level Questions - Part 7

801. How do you use Angular's `@Inject` for dependency injection?

Use @Inject to specify the token for dependency injection:

import { Injectable, Inject } from '@angular/core';
import { MY_TOKEN } from './tokens';

@Injectable({
  providedIn: 'root'
})
export class MyService {
  constructor(@Inject(MY_TOKEN) private myValue: string) {}
}
            

802. How do you use Angular's `@Optional` to handle optional dependencies?

Use @Optional to inject dependencies that may or may not be provided:

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

@Injectable({
  providedIn: 'root'
})
export class MyService {
  constructor(@Optional() private optionalDependency?: SomeService) {}
}
            

803. How do you use Angular's `ngAfterViewInit` lifecycle hook?

Implement ngAfterViewInit to perform actions after the component's view has been initialized:

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

@Component({
  selector: 'app-after-view',
  template: \`<p #pElement>Content</p>\`
})
export class AfterViewComponent implements AfterViewInit {
  @ViewChild('pElement') pElement: ElementRef;

  ngAfterViewInit() {
    console.log(this.pElement.nativeElement.textContent);
  }
}
            

804. How do you use Angular's `ngOnChanges` lifecycle hook to detect changes in input properties?

Use ngOnChanges to react to changes in input properties:

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

@Component({
  selector: 'app-on-changes',
  template: \`<p>{{inputProp}}</p>\`
})
export class OnChangesComponent implements OnChanges {
  @Input() inputProp: string;

  ngOnChanges(changes: SimpleChanges) {
    console.log('Changes:', changes);
  }
}
            

805. How do you use Angular's `ngDoCheck` to implement custom change detection?

Implement ngDoCheck to customize change detection behavior:

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

@Component({
  selector: 'app-do-check',
  template: \`<p>Custom Change Detection</p>\`
})
export class DoCheckComponent implements DoCheck {
  ngDoCheck() {
    console.log('Custom change detection');
  }
}
            

806. How do you use Angular's `ngOnInit` to initialize component data?

Initialize data using ngOnInit:

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

@Component({
  selector: 'app-on-init',
  template: \`<p>Initialized Data: {{data}}</p>\`
})
export class OnInitComponent implements OnInit {
  data: string;

  ngOnInit() {
    this.data = 'Initial Data';
  }
}
            

807. How do you use Angular's `ngOnDestroy` to clean up resources?

Use ngOnDestroy to perform cleanup tasks:

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

@Component({
  selector: 'app-on-destroy',
  template: \`<p>Cleanup Example</p>\`
})
export class OnDestroyComponent implements OnDestroy {
  ngOnDestroy() {
    console.log('Cleanup tasks');
  }
}
            

808. How do you use Angular's `@ViewChild` to get a reference to a child component or DOM element?

Access child components or DOM elements using @ViewChild:

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

@Component({
  selector: 'app-view-child',
  template: \`<input #inputElement>\`
})
export class ViewChildComponent {
  @ViewChild('inputElement') inputElement: ElementRef;

  ngAfterViewInit() {
    this.inputElement.nativeElement.focus();
  }
}
            

809. How do you use Angular's `@ContentChild` to get a reference to a projected content?

Query projected content using @ContentChild:

import { Component, ContentChild, AfterContentInit } from '@angular/core';
import { ContentComponent } from './content.component';

@Component({
  selector: 'app-content-child',
  template: \`<ng-content></ng-content>\`
})
export class ContentChildComponent implements AfterContentInit {
  @ContentChild(ContentComponent) contentChild: ContentComponent;

  ngAfterContentInit() {
    console.log(this.contentChild);
  }
}
            

810. How do you use Angular's `@ViewChildren` and `@ContentChildren` to query multiple elements or components?

Query multiple elements or components using @ViewChildren and @ContentChildren:

import { Component, ViewChildren, QueryList, AfterViewInit } from '@angular/core';
import { ChildComponent } from './child.component';

@Component({
  selector: 'app-view-children',
  template: \`<app-child></app-child><app-child></app-child>\`
})
export class ViewChildrenComponent implements AfterViewInit {
  @ViewChildren(ChildComponent) children: QueryList<ChildComponent>;

  ngAfterViewInit() {
    this.children.forEach(child => console.log(child));
  }
}
            

811. How do you use Angular's `@HostBinding` to bind host element properties?

Use @HostBinding to bind properties to the host element:

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

@Directive({
  selector: '[appHostBinding]'
})
export class HostBindingDirective {
  @HostBinding('class.highlight') isHighlighted = true;
}
            

812. How do you use Angular's `@HostListener` to listen for events on the host element?

Listen to events on the host element using @HostListener:

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

@Directive({
  selector: '[appHostListener]'
})
export class HostListenerDirective {
  @HostListener('mouseenter') onMouseEnter() {
    console.log('Mouse entered');
  }
}
            

813. How do you use Angular's `@Pipe` to transform data in templates?

Create a custom pipe to transform data:

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

@Pipe({
  name: 'customPipe'
})
export class CustomPipe implements PipeTransform {
  transform(value: string): string {
    return value.toUpperCase();
  }
}
            

814. How do you use Angular's `NgZone` to manage change detection manually?

Use NgZone to control change detection:

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

@Component({
  selector: 'app-ng-zone',
  template: \`<p>NgZone Example</p>\`
})
export class NgZoneComponent {
  constructor(private ngZone: NgZone) {}

  runOutsideAngular() {
    this.ngZone.runOutsideAngular(() => {
      // Code that doesn't trigger change detection
    });
  }

  runInsideAngular() {
    this.ngZone.run(() => {
      // Code that triggers change detection
    });
  }
}
            

815. How do you use Angular's `Renderer2` to manipulate the DOM?

Use Renderer2 for DOM manipulation:

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

@Component({
  selector: 'app-renderer',
  template: \`<p>Renderer2 Example</p>\`
})
export class RendererComponent {
  constructor(private renderer: Renderer2, private el: ElementRef) {}

  ngAfterViewInit() {
    this.renderer.setStyle(this.el.nativeElement.querySelector('p'), 'color', 'blue');
  }
}
            

816. How do you use Angular's `ChangeDetectorRef` to manually trigger change detection?

Manually trigger change detection using ChangeDetectorRef:

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

@Component({
  selector: 'app-change-detector',
  template: \`<p>Change Detection Example</p>\`
})
export class ChangeDetectorComponent {
  constructor(private cdr: ChangeDetectorRef) {}

  triggerChangeDetection() {
    this.cdr.detectChanges();
  }
}
            

817. How do you use Angular's `HttpInterceptor` to handle HTTP requests and responses?

Implement HttpInterceptor to intercept HTTP requests and responses:

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const authReq = req.clone({
      headers: req.headers.set('Authorization', 'Bearer token')
    });
    return next.handle(authReq);
  }
}
            
 

Angular Advanced Level Questions - Part 9

818. How do you use Angular's `NgModule` to configure a module with custom providers?

Configure a module with custom providers using @NgModule:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MyComponent } from './my-component.component';
import { MyService } from './my-service.service';

@NgModule({
  declarations: [MyComponent],
  imports: [CommonModule],
  providers: [
    { provide: MyService, useClass: MyCustomService }
  ]
})
export class MyModule {}
            

819. How do you use Angular's `@Input` to bind parent component data to child components?

Bind parent data to child components using @Input:

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

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

@Component({
  selector: 'app-parent',
  template: \`<app-child [parentData]="data"></app-child>\`
})
export class ParentComponent {
  data = 'Data from parent';
}
            

820. How do you use Angular's `@Output` to emit events from child components to parent components?

Emit events from child to parent using @Output:

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

@Component({
  selector: 'app-child',
  template: \`<button (click)="notifyParent()">Notify</button>\`
})
export class ChildComponent {
  @Output() notify: EventEmitter<string> = new EventEmitter<string>();

  notifyParent() {
    this.notify.emit('Message from child');
  }
}

@Component({
  selector: 'app-parent',
  template: \`<app-child (notify)="receiveMessage($event)"></app-child>\`
})
export class ParentComponent {
  receiveMessage(message: string) {
    console.log(message);
  }
}
            

821. How do you use Angular's `@HostBinding` to bind host properties?

Bind host properties using @HostBinding:

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

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  @HostBinding('style.backgroundColor') backgroundColor = 'yellow';
}
            

822. How do you use Angular's `@HostListener` to listen to host events?

Listen to host events using @HostListener:

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

@Directive({
  selector: '[appHover]'
})
export class HoverDirective {
  @HostListener('mouseenter') onMouseEnter() {
    console.log('Mouse entered');
  }

  @HostListener('mouseleave') onMouseLeave() {
    console.log('Mouse left');
  }
}
            

823. How do you use Angular's `ChangeDetectionStrategy` to optimize performance?

Optimize performance using ChangeDetectionStrategy:

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

@Component({
  selector: 'app-optimized',
  template: \`<p>Optimized Change Detection</p>\`,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class OptimizedComponent {}
            

824. How do you use Angular's `ChangeDetectorRef` to manually trigger change detection?

Manually trigger change detection using ChangeDetectorRef:

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

@Component({
  selector: 'app-manual-detection',
  template: \`<p>Manual Change Detection</p>\`
})
export class ManualDetectionComponent {
  constructor(private cdr: ChangeDetectorRef) {}

  triggerChangeDetection() {
    this.cdr.detectChanges();
  }
}
            

825. How do you use Angular's `Renderer2` to safely manipulate the DOM?

Safely manipulate the DOM using Renderer2:

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

@Component({
  selector: 'app-dom-manipulation',
  template: \`<p>DOM Manipulation Example</p>\`
})
export class DomManipulationComponent {
  constructor(private renderer: Renderer2, private el: ElementRef) {}

  ngAfterViewInit() {
    this.renderer.setStyle(this.el.nativeElement.querySelector('p'), 'color', 'blue');
  }
}
            

826. How do you use Angular's `HttpInterceptor` to modify HTTP requests and responses?

Modify HTTP requests and responses using HttpInterceptor:

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class MyInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const modifiedReq = req.clone({
      headers: req.headers.set('Authorization', 'Bearer your-token')
    });
    return next.handle(modifiedReq);
  }
}
            

827. How do you use Angular's `NgZone` to run code inside or outside Angular's change detection?

Run code inside or outside change detection using NgZone:

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

@Component({
  selector: 'app-ng-zone',
  template: \`<p>NgZone Example</p>\`
})
export class NgZoneComponent {
  constructor(private ngZone: NgZone) {}

  runOutsideAngular() {
    this.ngZone.runOutsideAngular(() => {
      // Code not affecting Angular change detection
    });
  }

  runInsideAngular() {
    this.ngZone.run(() => {
      // Code affecting Angular change detection
    });
  }
}
            

828. How do you use Angular's `NgModule` to set up routing with lazy-loaded feature modules?

Set up routing with lazy-loaded modules using NgModule:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

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

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

829. How do you use Angular's `@Component` decorator to define custom template and styles?

Define custom template and styles using @Component:

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

@Component({
  selector: 'app-custom',
  template: \`<p>Custom Template</p>\`,
  styles: [\`p { color: red; } \`]
})
export class CustomComponent {}
            

830. How do you use Angular's `@Injectable` to configure dependency injection in services?

Configure dependency injection in services using @Injectable:

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

@Injectable({
  providedIn: 'root'
})
export class MyService {
  constructor() {}
}
            

831. How do you use Angular's `FormArray` to manage dynamic forms?

Manage dynamic forms using FormArray:

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';

@Component({
  selector: 'app-dynamic-form',
  template: \`
    <form [formGroup]="form">
      <div formArrayName="items">
        <div *ngFor="let item of items.controls; let i = index">
          <input [formControlName]="i" />
        </div>
      </div>
    </form>
    <button (click)="addItem()">Add Item</button>
  \`
})
export class DynamicFormComponent {
  form: FormGroup;

  get items() {
    return this.form.get('items') as FormArray;
  }

  constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
      items: this.fb.array([])
    });
  }

  addItem() {
    this.items.push(this.fb.control(''));
  }
}
            

832. How do you use Angular's `ActivatedRoute` to access route parameters?

Access route parameters using ActivatedRoute:

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

@Component({
  selector: 'app-route-params',
  template: \`<p>Route Parameter: {{ id }}</p>\`
})
export class RouteParamsComponent implements OnInit {
  id: string;

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.route.paramMap.subscribe(params => {
      this.id = params.get('id');
    });
  }
}
            

833. How do you use Angular's `Router` to programmatically navigate?

Navigate programmatically using Router:

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

@Component({
  selector: 'app-navigation',
  template: \`<button (click)="navigate()">Navigate</button>\`
})
export class NavigationComponent {
  constructor(private router: Router) {}

  navigate() {
    this.router.navigate(['/path']);
  }
}
            

834. How do you use Angular's `@NgModule` to provide a singleton service across the application?

Provide a singleton service across the application using @NgModule:

import { NgModule } from '@angular/core';
import { MyService } from './my-service.service';

@NgModule({
  providers: [MyService]
})
export class AppModule {}
            

835. How do you use Angular's `HttpClient` to handle HTTP operations?

Handle HTTP operations using HttpClient:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class DataService {
  constructor(private http: HttpClient) {}

  getData(): Observable<any> {
    return this.http.get('https://api.example.com/data');
  }
}
            

836. How do you use Angular's `AsyncPipe` to handle asynchronous data?

Handle asynchronous data using AsyncPipe:

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

@Component({
  selector: 'app-async-pipe',
  template: \`<p>{{ data$ | async }}</p>\`
})
export class AsyncPipeComponent {
  data$: Observable<string> = new Observable(observer => {
    observer.next('Asynchronous Data');
    observer.complete();
  });
}
            

837. How do you use Angular's `@ViewChild` to access child components or directives?

Access child components or directives using @ViewChild:

import { Component, ViewChild } from '@angular/core';
import { ChildComponent } from './child.component';

@Component({
  selector: 'app-parent',
  template: \`<app-child></app-child>\`
})
export class ParentComponent {
  @ViewChild(ChildComponent) child: ChildComponent;

  ngAfterViewInit() {
    console.log(this.child.someProperty);
  }
}
            

 

Angular Advanced Level Questions - Part 10

838. How do you use Angular's `@ViewChild` to get a reference to a DOM element?

Get a reference to a DOM element using @ViewChild:

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

@Component({
  selector: 'app-view-child',
  template: \`<div #myDiv>Content</div>\`
})
export class ViewChildComponent implements AfterViewInit {
  @ViewChild('myDiv') div: ElementRef;

  ngAfterViewInit() {
    console.log(this.div.nativeElement.textContent);
  }
}
            

839. How do you use Angular's `@ContentChild` to access projected content?

Access projected content using @ContentChild:

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

@Component({
  selector: 'app-content-child',
  template: \`<ng-content></ng-content>\`
})
export class ContentChildComponent implements AfterContentInit {
  @ContentChild('projectedContent') content: ElementRef;

  ngAfterContentInit() {
    console.log(this.content.nativeElement.textContent);
  }
}
            

840. How do you use Angular's `@Directive` to create a custom directive that changes the appearance of an element?

Create a custom directive using @Directive:

import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  constructor(private el: ElementRef, private renderer: Renderer2) {}

  @HostListener('mouseenter') onMouseEnter() {
    this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow');
  }

  @HostListener('mouseleave') onMouseLeave() {
    this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'transparent');
  }
}
            

841. How do you use Angular's `HttpClient` to perform a POST request with a JSON payload?

Perform a POST request using HttpClient:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ApiService {
  constructor(private http: HttpClient) {}

  postData(data: any): Observable<any> {
    return this.http.post('https://api.example.com/data', data);
  }
}
            

842. How do you use Angular's `Router` to navigate with query parameters?

Navigate with query parameters using Router:

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

@Component({
  selector: 'app-query-params',
  template: \`<button (click)="navigate()">Navigate</button>\`
})
export class QueryParamsComponent {
  constructor(private router: Router) {}

  navigate() {
    this.router.navigate(['/path'], { queryParams: { page: 1, sort: 'asc' } });
  }
}
            

843. How do you use Angular's `ActivatedRoute` to retrieve query parameters from the route?

Retrieve query parameters using ActivatedRoute:

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

@Component({
  selector: 'app-query-params',
  template: \`<p>Page: {{ page }}, Sort: {{ sort }}</p>\`
})
export class QueryParamsComponent implements OnInit {
  page: number;
  sort: string;

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.route.queryParams.subscribe(params => {
      this.page = +params['page'];
      this.sort = params['sort'];
    });
  }
}
            

844. How do you use Angular's `ng-template` to create conditional templates?

Create conditional templates using ng-template:

<ng-container *ngIf="isVisible; else noContent">
  <p>Content is visible</p>
</ng-container>

<ng-template #noContent>
  <p>Content is hidden</p>
</ng-template>
            

845. How do you use Angular's `ngIf` and `ngFor` directives together?

Use ngIf and ngFor together:

<div *ngIf="items.length > 0">
  <ul>
    <li *ngFor="let item of items">{{ item }}</li>
  </ul>
</div>
            

846. How do you use Angular's `NgSwitch` to display content based on a variable's value?

Display content based on a variable using NgSwitch:

<div [ngSwitch]="value">
  <p *ngSwitchCase="'one'">One</p>
  <p *ngSwitchCase="'two'">Two</p>
  <p *ngSwitchDefault>Default</p>
</div>
            

847. How do you use Angular's `ngStyle` to apply styles conditionally?

Apply styles conditionally using ngStyle:

<div [ngStyle]="{ 'background-color': isActive ? 'yellow' : 'transparent' }">
  Conditional Styling
</div>
            

848. How do you use Angular's `ngClass` to add or remove classes dynamically?

Add or remove classes dynamically using ngClass:

<div [ngClass]="{ 'active': isActive, 'disabled': !isActive }">
  Dynamic Classes
</div>
            

849. How do you use Angular's `FormControl` to manage individual form inputs?

Manage individual form inputs using FormControl:

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

@Component({
  selector: 'app-form-control',
  template: \`
    <input [formControl]="control" />
    <p>Value: {{ control.value }}</p>
  \`
})
export class FormControlComponent {
  control = new FormControl('');
}
            

850. How do you use Angular's `FormBuilder` to create a form with nested controls?

Create a form with nested controls using FormBuilder:

import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-nested-form',
  template: \`
    <form [formGroup]="form">
      <div formGroupName="address">
        <input formControlName="street" />
        <input formControlName="city" />
      </div>
    </form>
  \`
})
export class NestedFormComponent {
  form: FormGroup;

  constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
      address: this.fb.group({
        street: '',
        city: ''
      })
    });
  }
}
            

851. How do you use Angular's `FormGroup` to group form controls?

Group form controls using FormGroup:

import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-form-group',
  template: \`
    <form [formGroup]="form">
      <input formControlName="name" />
      <input formControlName="email" />
    </form>
  \`
})
export class FormGroupComponent {
  form: FormGroup;

  constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
      name: '',
      email: ''
    });
  }
}
            

852. How do you use Angular's `AbstractControl` to work with form controls?

Work with form controls using AbstractControl:

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, AbstractControl } from '@angular/forms';

@Component({
  selector: 'app-abstract-control',
  template: \`
    <form [formGroup]="form">
      <input [formControl]="nameControl" />
    </form>
  \`
})
export class AbstractControlComponent {
  form: FormGroup;

  get nameControl(): AbstractControl {
    return this.form.get('name');
  }

  constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
      name: ''
    });
  }
}
            

853. How do you use Angular's `Custom Validators` to validate form controls?

Create custom validators for form controls:

import { AbstractControl, ValidatorFn } from '@angular/forms';

export function forbiddenNameValidator(name: string): ValidatorFn {
  return (control: AbstractControl): { [key: string]: any } | null => {
    const forbidden = control.value === name;
    return forbidden ? { 'forbiddenName': { value: control.value } } : null;
  };
}
            

854. How do you use Angular's `ChangeDetectorRef` to manually trigger change detection?

Manually trigger change detection using ChangeDetectorRef:

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

@Component({
  selector: 'app-manual-detection',
  template: \`<p>Manual Detection</p>\`
})
export class ManualDetectionComponent {
  constructor(private cdr: ChangeDetectorRef) {}

  triggerChangeDetection() {
    this.cdr.detectChanges();
  }
}
            

855. How do you use Angular's `OnPush` change detection strategy to optimize performance?

Optimize performance using OnPush change detection strategy:

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

@Component({
  selector: 'app-on-push',
  template: \`<p>OnPush Strategy</p>\`,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class OnPushComponent {}
            

856. How do you use Angular's `Dynamic Components` to load components dynamically?

Load components dynamically using ComponentFactoryResolver:

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

@Component({
  selector: 'app-dynamic',
  template: \`<ng-container #container></ng-container>\`
})
export class DynamicComponent implements OnInit {
  constructor(private cfr: ComponentFactoryResolver, private vcr: ViewContainerRef) {}

  ngOnInit() {
    const factory = this.cfr.resolveComponentFactory(SomeComponent);
    this.vcr.createComponent(factory);
  }
}
            

857. How do you use Angular's `NgModule` to configure a feature module with lazy loading?

Configure a feature module with lazy loading using NgModule:

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

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

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

 

Angular Advanced Level Questions - Part 11

858. How do you use Angular's `Renderer2` to manipulate the DOM safely?

Manipulate the DOM using Renderer2:

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

@Component({
  selector: 'app-renderer',
  template: \`<div #myDiv>Content</div>\`
})
export class RendererComponent {
  constructor(private renderer: Renderer2, private el: ElementRef) {}

  changeBackgroundColor() {
    this.renderer.setStyle(this.el.nativeElement.querySelector('div'), 'backgroundColor', 'blue');
  }
}
            

859. How do you use Angular's `HttpInterceptor` to handle HTTP requests and responses globally?

Handle HTTP requests and responses using HttpInterceptor:

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const clonedRequest = req.clone({
      headers: req.headers.set('Authorization', 'Bearer your-token')
    });
    return next.handle(clonedRequest);
  }
}
            

860. How do you use Angular's `Dependency Injection` to provide services in a hierarchical injector?

Provide services using hierarchical injectors:

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

@Injectable({
  providedIn: 'root' // Service provided at root level
})
export class SharedService {
  constructor() {}
}
            

861. How do you use Angular's `Router` to implement route guards for authentication?

Implement route guards for authentication using Router:

import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(private router: Router) {}

  canActivate(): Observable<boolean> | Promise<boolean> | boolean {
    const isAuthenticated = false; // Replace with real authentication check
    if (!isAuthenticated) {
      this.router.navigate(['/login']);
      return false;
    }
    return true;
  }
}
            

862. How do you use Angular's `ChangeDetectorRef` to manually check for changes in a component?

Manually check for changes using ChangeDetectorRef:

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

@Component({
  selector: 'app-detection',
  template: \`<p>Manual Change Detection</p>\`
})
export class DetectionComponent {
  constructor(private cdr: ChangeDetectorRef) {}

  triggerCheck() {
    this.cdr.detectChanges();
  }
}
            

863. How do you use Angular's `NgZone` to run code outside the Angular zone?

Run code outside the Angular zone using NgZone:

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

@Component({
  selector: 'app-ng-zone',
  template: \`<p>NgZone Example</p>\`
})
export class NgZoneComponent {
  constructor(private ngZone: NgZone) {}

  runOutsideAngular() {
    this.ngZone.runOutsideAngular(() => {
      // Code here won't trigger Angular change detection
    });
  }
}
            

864. How do you use Angular's `@Inject` decorator to inject dependencies?

Inject dependencies using @Inject:

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

const TOKEN = 'my-token';

@Injectable({
  providedIn: 'root'
})
export class MyService {
  constructor(@Inject(TOKEN) private token: string) {}
}
            

865. How do you use Angular's `@HostListener` decorator to listen to DOM events?

Listen to DOM events using @HostListener:

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

@Directive({
  selector: '[appHostListener]'
})
export class HostListenerDirective {
  @HostListener('click', ['$event'])
  onClick(event: Event) {
    console.log('Element clicked', event);
  }
}
            

866. How do you use Angular's `@HostBinding` decorator to bind properties to the host element?

Bind properties to the host element using @HostBinding:

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

@Directive({
  selector: '[appHostBinding]'
})
export class HostBindingDirective {
  @HostBinding('attr.aria-label') ariaLabel = 'Host Element';
}
            

867. How do you use Angular's `ng-container` to avoid adding extra elements to the DOM?

Use ng-container to avoid adding extra elements:

<ng-container *ngIf="isVisible">
  <p>This will be displayed if isVisible is true</p>
</ng-container>
            

868. How do you use Angular's `@ViewChildren` to get references to multiple DOM elements?

Get references to multiple DOM elements using @ViewChildren:

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

@Component({
  selector: 'app-view-children',
  template: \`<div #item *ngFor="let i of items">Item {{ i }}</div>\`
})
export class ViewChildrenComponent implements AfterViewInit {
  @ViewChildren('item') items: QueryList<ElementRef>;

  ngAfterViewInit() {
    this.items.forEach(item => console.log(item.nativeElement.textContent));
  }
}
            

869. How do you use Angular's `@ContentChildren` to get references to multiple projected content elements?

Get references to multiple projected content elements using @ContentChildren:

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

@Component({
  selector: 'app-content-children',
  template: \`<ng-content></ng-content>\`
})
export class ContentChildrenComponent implements AfterContentInit {
  @ContentChildren('contentItem') contentItems: QueryList<ElementRef>;

  ngAfterContentInit() {
    this.contentItems.forEach(item => console.log(item.nativeElement.textContent));
  }
}
            

870. How do you use Angular's `@Input` and `@Output` decorators to pass data between components?

Pass data between components using @Input and @Output:

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

@Component({
  selector: 'app-child',
  template: \`<button (click)="sendMessage()">Send</button>\`
})
export class ChildComponent {
  @Input() parentData: string;
  @Output() messageEvent = new EventEmitter<string>();

  sendMessage() {
    this.messageEvent.emit('Message from child');
  }
}

@Component({
  selector: 'app-parent',
  template: \`
    <app-child [parentData]="data" (messageEvent)="receiveMessage($event)"></app-child>
  \`
})
export class ParentComponent {
  data = 'Data from parent';

  receiveMessage(message: string) {
    console.log(message);
  }
}
            

871. How do you use Angular's `@ViewChild` to get a reference to a child component or DOM element?

Get a reference to a child component or DOM element using @ViewChild:

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

@Component({
  selector: 'app-view-child',
  template: \`<div #myDiv>Child Div</div>\`
})
export class ViewChildComponent implements AfterViewInit {
  @ViewChild('myDiv') myDiv: ElementRef;

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

872. How do you use Angular's `ChangeDetectionStrategy` to manage change detection behavior?

Manage change detection behavior using ChangeDetectionStrategy:

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

@Component({
  selector: 'app-change-detection',
  template: \`<p>Change Detection Strategy</p>\`,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChangeDetectionComponent {}
            

873. How do you use Angular's `ngIf` and `ngFor` directives to conditionally display and iterate over elements?

Use ngIf and ngFor directives to conditionally display and iterate over elements:

<div *ngIf="isVisible">
  <div *ngFor="let item of items">{{ item }}</div>
</div>
            

874. How do you use Angular's `ng-template` to define reusable template blocks?

Define reusable template blocks using ng-template:

<ng-template #myTemplate>
  <p>Reusable Content</p>
</ng-template>

<ng-container *ngTemplateOutlet="myTemplate"></ng-container>
            

875. How do you use Angular's `ContentProjection` to project content into a component?

Project content into a component using ContentProjection:

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

@Component({
  selector: 'app-content-projection',
  template: \`
    <ng-content></ng-content>
  \`
})
export class ContentProjectionComponent {}
            

876. How do you use Angular's `Dependency Injection` to provide different instances of a service?

Provide different instances of a service using Dependency Injection:

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

@Injectable({
  providedIn: 'root'
})
export class MyService {
  constructor() {}
}

@Injectable({
  providedIn: 'root',
  useClass: DifferentService
})
export class AlternativeService {}
            

877. How do you use Angular's `Router` to handle child routes?

Handle child routes using Router:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { ParentComponent } from './parent.component';
import { ChildComponent } from './child.component';

const routes: Routes = [
  {
    path: 'parent',
    component: ParentComponent,
    children: [
      { path: 'child', component: ChildComponent }
    ]
  }
];

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

 

Angular Advanced Level Questions - Part 12

878. How do you use Angular's `NgModule` to configure lazy-loaded modules?

Configure lazy-loaded modules using NgModule:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { CommonModule } from '@angular/common';
import { LazyModule } from './lazy/lazy.module';

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

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

879. How do you use Angular's `@ViewEncapsulation` to control the encapsulation of styles?

Control style encapsulation using @ViewEncapsulation:

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

@Component({
  selector: 'app-encapsulation',
  template: \`<p>Style Encapsulation</p>\`,
  styles: [\`
    p { color: blue; }
  \`],
  encapsulation: ViewEncapsulation.None // No encapsulation
})
export class EncapsulationComponent {}
            

880. How do you use Angular's `NgModule` to import and use third-party libraries?

Import and use third-party libraries in NgModule:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; // Example third-party library

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    NgbModule // Import third-party module
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}
            

881. How do you use Angular's `HttpClient` to make HTTP requests and handle responses?

Make HTTP requests and handle responses using HttpClient:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ApiService {
  constructor(private http: HttpClient) {}

  getData(): Observable<any> {
    return this.http.get('https://api.example.com/data');
  }
}
            

882. How do you use Angular's `FormArray` to manage dynamic forms?

Manage dynamic forms using FormArray:

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';

@Component({
  selector: 'app-dynamic-form',
  template: \`
    <form [formGroup]="form">
      <div formArrayName="items">
        <div *ngFor="let item of items.controls; let i = index">
          <input [formControlName]="i">
        </div>
      </div>
    </form>
    <button (click)="addItem()">Add Item</button>
  \`
})
export class DynamicFormComponent {
  form: FormGroup;

  get items(): FormArray {
    return this.form.get('items') as FormArray;
  }

  constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
      items: this.fb.array([])
    });
  }

  addItem() {
    this.items.push(this.fb.control(''));
  }
}
            

883. How do you use Angular's `@Pipe` decorator to create custom pipes?

Create custom pipes using @Pipe:

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

@Pipe({
  name: 'customPipe'
})
export class CustomPipe implements PipeTransform {
  transform(value: string): string {
    return value.toUpperCase();
  }
}
            

884. How do you use Angular's `ChangeDetectorRef` to manually trigger change detection?

Trigger change detection manually using ChangeDetectorRef:

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

@Component({
  selector: 'app-change-detection',
  template: \`<p>Change Detection</p>\`
})
export class ChangeDetectionComponent {
  constructor(private cdr: ChangeDetectorRef) {}

  updateView() {
    this.cdr.detectChanges(); // Manually trigger change detection
  }
}
            

885. How do you use Angular's `@HostListener` to listen to host element events?

Listen to host element events using @HostListener:

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

@Directive({
  selector: '[appHostListener]'
})
export class HostListenerDirective {
  @HostListener('click', ['$event'])
  onClick(event: Event) {
    console.log('Host element clicked:', event);
  }
}
            

886. How do you use Angular's `@ViewChild` to get a reference to a child component?

Get a reference to a child component using @ViewChild:

import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { ChildComponent } from './child.component';

@Component({
  selector: 'app-parent',
  template: \`<app-child></app-child>\`
})
export class ParentComponent implements AfterViewInit {
  @ViewChild(ChildComponent) childComponent: ChildComponent;

  ngAfterViewInit() {
    console.log(this.childComponent);
  }
}
            

887. How do you use Angular's `@ContentChildren` to get references to multiple projected content elements?

Get references to multiple projected content elements using @ContentChildren:

import { Component, ContentChildren, QueryList, AfterContentInit } from '@angular/core';

@Component({
  selector: 'app-content',
  template: \`
    <ng-content></ng-content>
  \`
})
export class ContentComponent implements AfterContentInit {
  @ContentChildren('contentItem') contentItems: QueryList<ElementRef>;

  ngAfterContentInit() {
    this.contentItems.forEach(item => console.log(item.nativeElement.textContent));
  }
}
            

888. How do you use Angular's `NgZone` to execute code outside Angular's change detection?

Execute code outside Angular's change detection using NgZone:

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

@Component({
  selector: 'app-ng-zone',
  template: \`<p>NgZone Example</p>\`
})
export class NgZoneComponent {
  constructor(private ngZone: NgZone) {
    this.ngZone.runOutsideAngular(() => {
      // Code here runs outside Angular's change detection
    });
  }
}
            

889. How do you use Angular's `@Inject` decorator to inject services with different configurations?

Inject services with different configurations using @Inject:

import { Injectable, Inject } from '@angular/core';
import { APP_CONFIG, AppConfig } from './app-config';

@Injectable({
  providedIn: 'root'
})
export class ConfigService {
  constructor(@Inject(APP_CONFIG) private config: AppConfig) {}

  getConfig() {
    return this.config;
  }
}
            

890. How do you use Angular's `Router` to handle route guards for protecting routes?

Handle route guards using Router:

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

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(private router: Router) {}

  canActivate(): boolean {
    const isAuthenticated = false; // Replace with actual authentication check
    if (!isAuthenticated) {
      this.router.navigate(['/login']);
      return false;
    }
    return true;
  }
}
            

891. How do you use Angular's `Renderer2` to manipulate DOM elements safely?

Manipulate DOM elements safely using Renderer2:

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

@Component({
  selector: 'app-renderer',
  template: \`<div #myDiv>Content</div>\`
})
export class RendererComponent implements AfterViewInit {
  constructor(private renderer: Renderer2, private el: ElementRef) {}

  ngAfterViewInit() {
    const div = this.el.nativeElement.querySelector('div');
    this.renderer.setStyle(div, 'color', 'red');
  }
}
            

892. How do you use Angular's `HttpInterceptor` to modify HTTP requests and responses?

Modify HTTP requests and responses using HttpInterceptor:

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const clonedRequest = req.clone({
      setHeaders: {
        Authorization: 'Bearer your-token'
      }
    });
    return next.handle(clonedRequest);
  }
}
            

893. How do you use Angular's `Renderer2` to listen to DOM events?

Listen to DOM events using Renderer2:

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

@Component({
  selector: 'app-event-listener',
  template: \`<button #myButton>Click me</button>\`
})
export class EventListenerComponent implements AfterViewInit {
  constructor(private renderer: Renderer2, private el: ElementRef) {}

  ngAfterViewInit() {
    const button = this.el.nativeElement.querySelector('button');
    this.renderer.listen(button, 'click', () => {
      console.log('Button clicked!');
    });
  }
}
            

894. How do you use Angular's `HttpClient` to handle file uploads?

Handle file uploads using HttpClient:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class FileUploadService {
  constructor(private http: HttpClient) {}

  uploadFile(file: File): Observable<any> {
    const formData = new FormData();
    formData.append('file', file);
    return this.http.post('https://api.example.com/upload', formData);
  }
}
            

895. How do you use Angular's `@HostBinding` to bind properties to host elements?

Bind properties to host elements using @HostBinding:

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

@Directive({
  selector: '[appHostBinding]'
})
export class HostBindingDirective {
  @HostBinding('attr.role') role = 'button';
}
            

896. How do you use Angular's `@ContentChildren` to get references to projected content in a parent component?

Get references to projected content using @ContentChildren:

import { Component, ContentChildren, QueryList, AfterContentInit } from '@angular/core';

@Component({
  selector: 'app-content',
  template: \`
    <ng-content select="[contentItem]" *ngFor="let item of contentItems"></ng-content>
  \`
})
export class ContentComponent implements AfterContentInit {
  @ContentChildren('contentItem') contentItems: QueryList<ElementRef>;

  ngAfterContentInit() {
    this.contentItems.forEach(item => console.log(item.nativeElement.textContent));
  }
}
            

897. How do you use Angular's `Renderer2` to conditionally add and remove CSS classes?

Add and remove CSS classes conditionally using Renderer2:

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

@Component({
  selector: 'app-css-class',
  template: \`<div #myDiv>Content</div>\`
})
export class CssClassComponent implements AfterViewInit {
  constructor(private renderer: Renderer2, private el: ElementRef) {}

  ngAfterViewInit() {
    const div = this.el.nativeElement.querySelector('div');
    this.renderer.addClass(div, 'active');
    this.renderer.removeClass(div, 'inactive');
  }
}
            

 

Angular Advanced Level Questions - Part 13

898. How do you use Angular's `RxJS` operators to handle asynchronous operations?

Handle asynchronous operations using RxJS operators:

import { Component } from '@angular/core';
import { of } from 'rxjs';
import { delay, map } from 'rxjs/operators';

@Component({
  selector: 'app-rxjs',
  template: \`<p>Check console for RxJS example</p>\`
})
export class RxjsComponent {
  constructor() {
    of('Hello, World!')
      .pipe(
        delay(1000),
        map(message => message.toUpperCase())
      )
      .subscribe(result => console.log(result));
  }
}
            

899. How do you use Angular's `@Input` and `@Output` decorators to pass data between components?

Pass data between components using @Input and @Output:

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

@Component({
  selector: 'app-child',
  template: \`
    <button (click)="notifyParent()">Notify Parent</button>
  \`
})
export class ChildComponent {
  @Input() childData: string;
  @Output() notify: EventEmitter<string> = new EventEmitter<string>();

  notifyParent() {
    this.notify.emit('Hello from Child');
  }
}

@Component({
  selector: 'app-parent',
  template: \`
    <app-child [childData]="parentData" (notify)="onNotify($event)"></app-child>
  \`
})
export class ParentComponent {
  parentData = 'Data from Parent';

  onNotify(message: string) {
    console.log(message);
  }
}
            

900. How do you use Angular's `Router` to implement route parameter and query parameter handling?

Implement route and query parameter handling using Router:

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

@Component({
  selector: 'app-details',
  template: \`<p>ID: {{ id }} | Filter: {{ filter }}</p>\`
})
export class DetailsComponent implements OnInit {
  id: string;
  filter: string;

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.route.paramMap.subscribe(params => {
      this.id = params.get('id');
    });
    this.route.queryParamMap.subscribe(queryParams => {
      this.filter = queryParams.get('filter');
    });
  }
}
            

901. How do you use Angular's `Renderer2` to safely interact with the DOM?

Interact with the DOM safely using Renderer2:

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

@Component({
  selector: 'app-renderer',
  template: \`<div #myDiv>Content</div>\`
})
export class RendererComponent implements AfterViewInit {
  constructor(private renderer: Renderer2, private el: ElementRef) {}

  ngAfterViewInit() {
    const div = this.el.nativeElement.querySelector('div');
    this.renderer.setStyle(div, 'color', 'green');
  }
}
            

902. How do you use Angular's `ChangeDetectionStrategy` to optimize change detection?

Optimize change detection using ChangeDetectionStrategy:

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

@Component({
  selector: 'app-optimization',
  template: \`<p>Optimized Change Detection</p>\`,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class OptimizationComponent {}
            

903. How do you use Angular's `DynamicComponentLoader` to load components dynamically?

Load components dynamically using ComponentFactoryResolver:

import { Component, ComponentFactoryResolver, ViewChild, ViewContainerRef, OnInit } from '@angular/core';
import { DynamicComponent } from './dynamic.component';

@Component({
  selector: 'app-dynamic',
  template: \`<ng-template #dynamicContainer></ng-template>\`
})
export class DynamicComponentLoader implements OnInit {
  @ViewChild('dynamicContainer', { read: ViewContainerRef }) container: ViewContainerRef;

  constructor(private resolver: ComponentFactoryResolver) {}

  ngOnInit() {
    const factory = this.resolver.resolveComponentFactory(DynamicComponent);
    this.container.createComponent(factory);
  }
}
            

904. How do you use Angular's `Dependency Injection` to provide services in a module?

Provide services in a module using Dependency Injection:

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

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule],
  providers: [ApiService], // Provide service in module
  bootstrap: [AppComponent]
})
export class AppModule {}
            

905. How do you use Angular's `Router` to implement nested routes?

Implement nested routes using Router:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { ParentComponent } from './parent.component';
import { ChildComponent } from './child.component';

const routes: Routes = [
  {
    path: 'parent',
    component: ParentComponent,
    children: [
      { path: 'child', component: ChildComponent }
    ]
  }
];

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

906. How do you use Angular's `@NgModule` to configure providers for different environments?

Configure providers for different environments in NgModule:

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

export function initializeApp() {
  return (): Promise<any> => {
    // Initialize app based on environment
    return new Promise((resolve, reject) => {
      // Initialization logic here
      resolve(true);
    });
  };
}

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule],
  providers: [
    { provide: APP_INITIALIZER, useFactory: initializeApp, multi: true }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}
            

907. How do you use Angular's `@Injectable` decorator to create services with different scopes?

Create services with different scopes using @Injectable:

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

@Injectable({
  providedIn: 'root' // Singleton service
})
export class SingletonService {}

@Injectable({
  providedIn: 'any' // Scoped service
})
export class ScopedService {}
            

908. How do you use Angular's `@ViewChild` to access child components or DOM elements?

Access child components or DOM elements using @ViewChild:

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

@Component({
  selector: 'app-view-child',
  template: \`<div #myDiv>Content</div>\`
})
export class ViewChildComponent implements AfterViewInit {
  @ViewChild('myDiv') myDiv: ElementRef;

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

909. How do you use Angular's `@ContentChild` to access projected content in a component?

Access projected content using @ContentChild:

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

@Component({
  selector: 'app-content-child',
  template: \`<ng-content></ng-content>\`
})
export class ContentChildComponent implements AfterContentInit {
  @ContentChild('content') content: ElementRef;

  ngAfterContentInit() {
    console.log(this.content.nativeElement.textContent);
  }
}
            

910. How do you use Angular's `ChangeDetectorRef` to manually trigger change detection?

Trigger change detection manually using ChangeDetectorRef:

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

@Component({
  selector: 'app-change-detector',
  template: \`<p>Manual Change Detection</p>\`
})
export class ChangeDetectorComponent implements OnInit {
  constructor(private cdRef: ChangeDetectorRef) {}

  ngOnInit() {
    this.cdRef.detectChanges(); // Manually trigger change detection
  }
}
            

911. How do you use Angular's `FormBuilder` to create reactive forms?

Create reactive forms using FormBuilder:

import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-reactive-form',
  template: \`
    <form [formGroup]="form" (ngSubmit)="onSubmit()">
      <input formControlName="name" />
      <button type="submit">Submit</button>
    </form>
  \`
})
export class ReactiveFormComponent {
  form: FormGroup;

  constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
      name: ['']
    });
  }

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

912. How do you use Angular's `HttpClient` to handle file downloads?

Handle file downloads using HttpClient:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { saveAs } from 'file-saver';

@Injectable({
  providedIn: 'root'
})
export class FileDownloadService {
  constructor(private http: HttpClient) {}

  downloadFile(): Observable<Blob> {
    return this.http.get('https://api.example.com/download', { responseType: 'blob' });
  }

  saveFile() {
    this.downloadFile().subscribe(blob => {
      saveAs(blob, 'filename.ext');
    });
  }
}
            

913. How do you use Angular's `NgModule` to configure lazy-loaded modules?

Configure lazy-loaded modules using NgModule:

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

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

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

914. How do you use Angular's `Observable` to implement real-time data updates?

Implement real-time data updates using Observable:

import { Component, OnInit } from '@angular/core';
import { WebSocketSubject } from 'rxjs/webSocket';

@Component({
  selector: 'app-real-time',
  template: \`<p>Real-time Data: {{ data }}</p>\`
})
export class RealTimeComponent implements OnInit {
  data: any;
  private socket$: WebSocketSubject<any>;

  ngOnInit() {
    this.socket$ = new WebSocketSubject('wss://api.example.com/socket');
    this.socket$.subscribe(message => {
      this.data = message;
    });
  }
}
            

915. How do you use Angular's `NgZone` to optimize performance for heavy computations?

Optimize performance using NgZone:

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

@Component({
  selector: 'app-ng-zone',
  template: \`<p>NgZone Performance Optimization</p>\`
})
export class NgZoneComponent {
  constructor(private ngZone: NgZone) {
    this.ngZone.runOutsideAngular(() => {
      // Perform heavy computations here
      setTimeout(() => {
        console.log('Heavy computation done');
        this.ngZone.run(() => {
          // Update UI if needed
        });
      }, 1000);
    });
  }
}
            

916. How do you use Angular's `@Injectable` decorator to create multi-provider services?

Create multi-provider services using @Injectable:

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

export const API_URL = new InjectionToken<string>('apiUrl');

@Injectable({
  providedIn: 'root'
})
export class ApiService {
  constructor(@Inject(API_URL) private apiUrl: string) {}
}
            

917. How do you use Angular's `ChangeDetectorRef` to handle performance issues in large applications?

Handle performance issues using ChangeDetectorRef:

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

@Component({
  selector: 'app-performance',
  template: \`<p>Performance Optimized</p>\`
})
export class PerformanceComponent implements OnInit {
  constructor(private cdRef: ChangeDetectorRef) {}

  ngOnInit() {
    this.cdRef.detach(); // Detach change detection
    // Perform operations without triggering change detection
    this.cdRef.reattach(); // Reattach change detection if needed
  }
}
            

 

Angular Advanced Level Questions - Part 14

918. How do you create a custom Angular pipe?

To create a custom pipe, use the @Pipe decorator and implement the PipeTransform interface:

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

@Pipe({
  name: 'customPipe'
})
export class CustomPipe implements PipeTransform {
  transform(value: string, ...args: any[]): string {
    return value.toUpperCase(); // Example transformation
  }
}
            

919. How do you use Angular's `ng-content` to project content into a component?

Use ng-content to project content into a component:

<!-- Parent component template -->
<app-child>
  <p>This content is projected into the child component</p>
</app-child>

<!-- Child component template -->
<ng-content></ng-content>
            

920. How do you implement a custom form control in Angular?

To implement a custom form control, implement ControlValueAccessor:

import { Component, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

@Component({
  selector: 'app-custom-input',
  template: '<input (input)="onChange($event.target.value)" [value]="value">',
  providers: [{
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => CustomInputComponent),
    multi: true
  }]
})
export class CustomInputComponent implements ControlValueAccessor {
  value: string = '';
  onChange = (value: string) => {};
  onTouched = () => {};

  writeValue(value: string): void {
    this.value = value;
  }

  registerOnChange(fn: (value: string) => void): void {
    this.onChange = fn;
  }

  registerOnTouched(fn: () => void): void {
    this.onTouched = fn;
  }
}
            

921. How do you use Angular's Dependency Injection to provide services?

Provide services using Angular's Dependency Injection:

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

@Injectable({
  providedIn: 'root'
})
export class MyService {
  constructor() { }
}
            

922. How do you handle errors in Angular services using `HttpInterceptor`?

Handle errors using HttpInterceptor:

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http';
import { catchError, Observable, throwError } from 'rxjs';

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).pipe(
      catchError((error: HttpErrorResponse) => {
        console.error('Error occurred:', error);
        return throwError(error);
      })
    );
  }
}
            

923. How do you create an Angular module with lazy-loaded routes?

Create a module with lazy-loaded routes using RouterModule.forChild:

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

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

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

924. How do you use Angular's `@HostListener` decorator to listen to DOM events?

Use @HostListener to listen to DOM events:

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

@Directive({
  selector: '[appHover]'
})
export class HoverDirective {
  @HostListener('mouseover') onMouseOver() {
    console.log('Mouse over event');
  }

  @HostListener('mouseout') onMouseOut() {
    console.log('Mouse out event');
  }
}
            

925. How do you implement Angular's `ChangeDetectionStrategy`?

Implement ChangeDetectionStrategy to optimize change detection:

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

@Component({
  selector: 'app-optimized',
  template: '<p>Optimized Component</p>',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class OptimizedComponent { }
            

926. How do you use Angular's `@Injectable` decorator with different providers?

Use @Injectable with different providers:

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

@Injectable({
  providedIn: 'root' // Singleton service
})
export class DataService {
  constructor(private http: HttpClient) { }

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

@Injectable()
export class OtherService {
  constructor() { }
}
            

927. How do you handle Angular module dependencies and feature modules?

Handle module dependencies and feature modules:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FeatureComponent } from './feature.component';

@NgModule({
  declarations: [FeatureComponent],
  imports: [CommonModule],
  exports: [FeatureComponent]
})
export class FeatureModule { }
            

928. How do you use Angular's `Renderer2` to safely manipulate DOM elements?

Manipulate DOM elements safely using Renderer2:

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

@Component({
  selector: 'app-dom-manipulation',
  template: '<div #myDiv>Content</div>'
})
export class DomManipulationComponent {
  constructor(private renderer: Renderer2, private el: ElementRef) {}

  changeStyle() {
    const div = this.el.nativeElement.querySelector('#myDiv');
    this.renderer.setStyle(div, 'color', 'blue');
  }
}
            

929. How do you use Angular's `@ViewChild` to access child components and directives?

Access child components and directives using @ViewChild:

import { Component, ViewChild } from '@angular/core';
import { ChildComponent } from './child.component';

@Component({
  selector: 'app-parent',
  template: '<app-child></app-child>'
})
export class ParentComponent {
  @ViewChild(ChildComponent) child!: ChildComponent;

  callChildMethod() {
    this.child.someMethod();
  }
}
            

930. How do you use Angular's `@ContentChild` to access projected content?

Access projected content using @ContentChild:

import { Component, ContentChild, AfterContentInit } from '@angular/core';
import { ChildDirective } from './child.directive';

@Component({
  selector: 'app-parent',
  template: '<ng-content></ng-content>'
})
export class ParentComponent implements AfterContentInit {
  @ContentChild(ChildDirective) contentChild!: ChildDirective;

  ngAfterContentInit() {
    console.log(this.contentChild);
  }
}
            

931. How do you use Angular's `@HostBinding` to bind properties to host elements?

Bind properties to host elements using @HostBinding:

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

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  @HostBinding('class.highlight') isHighlighted = true;
}
            

932. How do you create an Angular service with multiple instances?

Create a service with multiple instances using providers in component metadata:

import { Component } from '@angular/core';
import { MyService } from './my.service';

@Component({
  selector: 'app-example',
  template: '<p>Example Component</p>',
  providers: [MyService] // New instance for this component
})
export class ExampleComponent {
  constructor(private myService: MyService) { }
}
            

933. How do you use Angular's `ChangeDetectorRef` to manually trigger change detection?

Trigger change detection manually using ChangeDetectorRef:

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

@Component({
  selector: 'app-manual-detection',
  template: '<p>Manual Change Detection</p>'
})
export class ManualDetectionComponent {
  constructor(private cdr: ChangeDetectorRef) { }

  triggerChangeDetection() {
    this.cdr.detectChanges();
  }
}
            

934. How do you use Angular's `ng-template` to create reusable templates?

Create reusable templates using ng-template:

<ng-template #template>
  <p>Reusable content</p>
</ng-template>

<ng-container *ngTemplateOutlet="template"></ng-container>
            

935. How do you use Angular's `@NgModule` to configure module imports and exports?

Configure imports and exports in @NgModule:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';

@NgModule({
  imports: [
    CommonModule,
    FormsModule
  ],
  exports: [
    CommonModule,
    FormsModule
  ]
})
export class SharedModule { }
            

936. How do you use Angular's `@Inject` to provide dependencies?

Provide dependencies using @Inject:

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

@Injectable({
  providedIn: 'root'
})
export class MyService {
  constructor(@Inject('API_URL') private apiUrl: string) { }
}
            

937. How do you create Angular custom decorators for components and services?

Create custom decorators by defining functions that return metadata:

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

function CustomDecorator(config: any) {
  return function (target: Function) {
    // Custom logic here
    console.log('Decorator applied with config:', config);
  };
}

@CustomDecorator({ key: 'value' })
@Component({
  selector: 'app-decorated',
  template: '<p>Custom Decorator Component</p>'
})
export class DecoratedComponent { }
            

 

Angular Advanced Level Questions - Part 15

938. How do you use Angular's `@HostListener` to listen to custom events?

Listen to custom events using @HostListener:

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

@Directive({
  selector: '[appCustomEvent]'
})
export class CustomEventDirective {
  @HostListener('customEvent', ['$event'])
  onCustomEvent(event: Event) {
    console.log('Custom event fired', event);
  }
}
            

939. How do you use Angular's `@ViewChildren` to access multiple child components?

Access multiple child components using @ViewChildren:

import { Component, ViewChildren, QueryList } from '@angular/core';
import { ChildComponent } from './child.component';

@Component({
  selector: 'app-parent',
  template: '<app-child *ngFor="let child of children"></app-child>'
})
export class ParentComponent {
  @ViewChildren(ChildComponent) children!: QueryList<ChildComponent>;

  ngAfterViewInit() {
    this.children.forEach(child => child.someMethod());
  }
}
            

940. How do you use Angular's `@ContentChildren` to access multiple projected content items?

Access multiple projected content items using @ContentChildren:

import { Component, ContentChildren, QueryList, AfterContentInit } from '@angular/core';
import { ProjectedComponent } from './projected.component';

@Component({
  selector: 'app-container',
  template: '<ng-content></ng-content>'
})
export class ContainerComponent implements AfterContentInit {
  @ContentChildren(ProjectedComponent) projectedItems!: QueryList<ProjectedComponent>;

  ngAfterContentInit() {
    this.projectedItems.forEach(item => item.doSomething());
  }
}
            

941. How do you handle Angular's router events to implement navigation guards?

Implement navigation guards using Router events:

import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(private router: Router) {}

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): boolean {
    const isAuthenticated = false; // Logic to check authentication
    if (!isAuthenticated) {
      this.router.navigate(['/login']);
      return false;
    }
    return true;
  }
}
            

942. How do you create a custom Angular validator for form controls?

Create a custom validator function:

import { AbstractControl, ValidatorFn } from '@angular/forms';

export function customValidator(): ValidatorFn {
  return (control: AbstractControl): { [key: string]: any } | null => {
    const isValid = /* custom validation logic */;
    return isValid ? null : { 'customError': true };
  };
}
            

943. How do you use Angular's `@Injectable` to inject tokens and configuration values?

Inject tokens and configuration values using @Inject:

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

@Injectable({
  providedIn: 'root'
})
export class ConfigService {
  constructor(@Inject('APP_CONFIG') private config: any) { }

  getConfig() {
    return this.config;
  }
}
            

944. How do you use Angular's `@Pipe` decorator to create a custom pipe?

Create a custom pipe using @Pipe:

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

@Pipe({
  name: 'reverse'
})
export class ReversePipe implements PipeTransform {
  transform(value: string): string {
    return value.split('').reverse().join('');
  }
}
            

945. How do you use Angular's `Router` to programmatically navigate between routes?

Navigate programmatically using Router:

import { Router } from '@angular/router';

constructor(private router: Router) {}

navigateToHome() {
  this.router.navigate(['/home']);
}
            

946. How do you use Angular's `HttpClient` to make HTTP requests and handle responses?

Make HTTP requests using HttpClient:

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

@Injectable({
  providedIn: 'root'
})
export class ApiService {
  constructor(private http: HttpClient) {}

  getData() {
    return this.http.get('/api/data').subscribe(response => {
      console.log(response);
    });
  }
}
            

947. How do you use Angular's `ChangeDetectionStrategy` to optimize performance?

Optimize performance using ChangeDetectionStrategy:

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

@Component({
  selector: 'app-performance',
  template: '<p>Optimized Component</p>',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class PerformanceComponent { }
            

948. How do you use Angular's `@Directive` to create custom behavior in your components?

Create custom behavior using @Directive:

import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  constructor(private el: ElementRef, private renderer: Renderer2) {}

  @HostListener('mouseenter') onMouseEnter() {
    this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow');
  }

  @HostListener('mouseleave') onMouseLeave() {
    this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'transparent');
  }
}
            

949. How do you use Angular's `@NgModule` to configure module imports and exports?

Configure module imports and exports using @NgModule:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FeatureComponent } from './feature.component';

@NgModule({
  imports: [CommonModule],
  declarations: [FeatureComponent],
  exports: [FeatureComponent]
})
export class FeatureModule { }
            

950. How do you use Angular's `@Optional` to provide optional dependencies?

Provide optional dependencies using @Optional:

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

@Injectable({
  providedIn: 'root'
})
export class MyService {
  constructor(@Optional() private optionalDependency?: AnyDependency) { }
}
            

951. How do you use Angular's `@Self` to provide dependencies only from the current injector?

Provide dependencies from the current injector using @Self:

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

@Injectable({
  providedIn: 'root'
})
export class MyService {
  constructor(@Self() private selfService: OtherService) { }
}
            

952. How do you use Angular's `ng-content` to create dynamic content projection?

Create dynamic content projection using ng-content:

<ng-content></ng-content>
            

953. How do you use Angular's `@Host` to inject dependencies from a parent component?

Inject dependencies from a parent component using @Host:

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

@Injectable({
  providedIn: 'root'
})
export class MyService {
  constructor(@Host() private parentService: ParentService) { }
}
            

954. How do you use Angular's `@ViewEncapsulation` to manage component styles?

Manage component styles using @ViewEncapsulation:

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

@Component({
  selector: 'app-styled',
  template: '<p>Styled Component</p>',
  styles: ['p { color: red; }'],
  encapsulation: ViewEncapsulation.None
})
export class StyledComponent { }
            

955. How do you use Angular's `ChangeDetectorRef` to manually trigger change detection?

Manually trigger change detection using ChangeDetectorRef:

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

@Component({
  selector: 'app-detect',
  template: '<p>Manual Change Detection</p>'
})
export class DetectComponent {
  constructor(private cdr: ChangeDetectorRef) { }

  triggerChange() {
    this.cdr.detectChanges();
  }
}
            

956. How do you use Angular's `@Directive` to create structural directives?

Create structural directives using @Directive:

import { Directive, TemplateRef, ViewContainerRef } from '@angular/core';

@Directive({
  selector: '[appUnless]'
})
export class UnlessDirective {
  constructor(private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) {}

  @Input() set appUnless(condition: boolean) {
    if (!condition) {
      this.viewContainer.createEmbeddedView(this.templateRef);
    } else {
      this.viewContainer.clear();
    }
  }
}
            

957. How do you use Angular's `@Host` and `@Self` to control dependency injection?

Control dependency injection using @Host and @Self:

import { Injectable, Host, Self } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class MyService {
  constructor(@Host() @Self() private parentService: ParentService) { }
}
            

 

Angular Advanced Level Questions - Part 16

958. How do you create a custom Angular directive to manipulate DOM elements?

Create a custom directive to manipulate DOM elements:

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

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  constructor(private el: ElementRef, private renderer: Renderer2) {
    this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow');
  }
}
            

959. How do you use Angular's `@Input` and `@Output` decorators to create component communication?

Component communication using @Input and @Output:

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

@Component({
  selector: 'app-child',
  template: '<button (click)="sendMessage()">Send Message</button>'
})
export class ChildComponent {
  @Input() childInput!: string;
  @Output() childOutput = new EventEmitter<string>();

  sendMessage() {
    this.childOutput.emit('Message from child');
  }
}

@Component({
  selector: 'app-parent',
  template: '<app-child [childInput]="parentData" (childOutput)="receiveMessage($event)"></app-child>'
})
export class ParentComponent {
  parentData = 'Data from parent';

  receiveMessage(message: string) {
    console.log(message);
  }
}
            

960. How do you create and use Angular services for state management?

Create and use services for state management:

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

@Injectable({
  providedIn: 'root'
})
export class StateService {
  private state = new BehaviorSubject<string>('initial state');
  currentState = this.state.asObservable();

  changeState(newState: string) {
    this.state.next(newState);
  }
}

import { Component, OnInit } from '@angular/core';
import { StateService } from './state.service';

@Component({
  selector: 'app-example',
  template: '<p>State: {{ state | async }}</p>'
})
export class ExampleComponent implements OnInit {
  state: Observable<string>;

  constructor(private stateService: StateService) {}

  ngOnInit() {
    this.state = this.stateService.currentState;
  }
}
            

961. How do you implement lazy loading of modules in Angular?

Implement lazy loading of modules:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LazyLoadedComponent } from './lazy-loaded.component';

const routes: Routes = [
  { path: 'lazy', component: LazyLoadedComponent }
];

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

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { LazyLoadedRoutingModule } from './lazy-loaded-routing.module';
import { LazyLoadedComponent } from './lazy-loaded.component';

@NgModule({
  declarations: [LazyLoadedComponent],
  imports: [
    CommonModule,
    LazyLoadedRoutingModule
  ]
})
export class LazyLoadedModule { }

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

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

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

962. How do you configure Angular CLI for production builds?

Configure Angular CLI for production builds in angular.json:

"architect": {
  "build": {
    "configurations": {
      "production": {
        "fileReplacements": [
          {
            "replace": "src/environments/environment.ts",
            "with": "src/environments/environment.prod.ts"
          }
        ],
        "optimization": true,
        "outputHashing": "all",
        "sourceMap": false,
        "extractCss": true,
        "namedChunks": false,
        "aot": true,
        "extractLicenses": true,
        "vendorChunk": false,
        "buildOptimizer": true,
        "serviceWorker": true
      }
    }
  }
}
            

963. How do you handle errors globally in Angular?

Handle errors globally using HttpInterceptor:

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpErrorResponse } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler) {
    return next.handle(req).pipe(
      catchError((error: HttpErrorResponse) => {
        console.error('Error occurred:', error);
        return throwError(error);
      })
    );
  }
}

import { NgModule } from '@angular/core';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { ErrorInterceptor } from './error.interceptor';

@NgModule({
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }
  ]
})
export class AppModule { }
            

964. How do you use Angular's `@NgModule` to define shared modules?

Define shared modules using @NgModule:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SharedComponent } from './shared.component';

@NgModule({
  declarations: [SharedComponent],
  imports: [CommonModule],
  exports: [SharedComponent]
})
export class SharedModule { }
            

965. How do you use Angular's `@Injectable` to create and use services with dependency injection?

Create and use services with dependency injection:

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

@Injectable({
  providedIn: 'root'
})
export class MyService {
  constructor() { }

  getServiceData() {
    return 'Service Data';
  }
}

import { Component, OnInit } from '@angular/core';
import { MyService } from './my.service';

@Component({
  selector: 'app-example',
  template: '<p>{{ data }}</p>'
})
export class ExampleComponent implements OnInit {
  data!: string;

  constructor(private myService: MyService) { }

  ngOnInit() {
    this.data = this.myService.getServiceData();
  }
}
            

966. How do you use Angular's `@HostListener` to listen to native DOM events?

Listen to native DOM events using @HostListener:

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

@Directive({
  selector: '[appClickTracker]'
})
export class ClickTrackerDirective {

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

967. How do you use Angular's `@ContentChild` to access projected content?

Access projected content using @ContentChild:

import { Component, ContentChild, AfterContentInit } from '@angular/core';
import { ChildComponent } from './child.component';

@Component({
  selector: 'app-parent',
  template: '<ng-content></ng-content>'
})
export class ParentComponent implements AfterContentInit {
  @ContentChild(ChildComponent) contentChild!: ChildComponent;

  ngAfterContentInit() {
    console.log('Projected content:', this.contentChild);
  }
}
            

968. How do you use Angular's `@ViewChild` to access a child component?

Access a child component using @ViewChild:

import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { ChildComponent } from './child.component';

@Component({
  selector: 'app-parent',
  template: '<app-child></app-child>'
})
export class ParentComponent implements AfterViewInit {
  @ViewChild(ChildComponent) childComponent!: ChildComponent;

  ngAfterViewInit() {
    console.log('Child component:', this.childComponent);
  }
}
            

969. How do you use Angular's `@Inject` to provide custom tokens for dependency injection?

Provide custom tokens using @Inject:

import { InjectionToken, Inject, Injectable } from '@angular/core';

export const MY_CUSTOM_TOKEN = new InjectionToken<string>('MyCustomToken');

@Injectable({
  providedIn: 'root'
})
export class MyService {
  constructor(@Inject(MY_CUSTOM_TOKEN) private token: string) {
    console.log('Token:', this.token);
  }
}
            

970. How do you use Angular's `@NgModule` to manage lazy-loaded feature modules?

Manage lazy-loaded feature modules using @NgModule:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FeatureRoutingModule } from './feature-routing.module';
import { FeatureComponent } from './feature.component';

@NgModule({
  declarations: [FeatureComponent],
  imports: [
    CommonModule,
    FeatureRoutingModule
  ]
})
export class FeatureModule { }

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

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

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

971. How do you use Angular's `ChangeDetectionStrategy` to optimize change detection?

Optimize change detection using ChangeDetectionStrategy:

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

@Component({
  selector: 'app-optimized',
  template: '<p>Optimized Change Detection</p>',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class OptimizedComponent { }
            

972. How do you use Angular's `@Pipe` to create custom pipes for data transformation?

Create custom pipes for data transformation:

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

@Pipe({
  name: 'reverse'
})
export class ReversePipe implements PipeTransform {
  transform(value: string): string {
    return value.split('').reverse().join('');
  }
}
            

973. How do you use Angular's `NgModule` to declare and import third-party modules?

Declare and import third-party modules in NgModule:

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

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

974. How do you use Angular's `@HostBinding` to bind properties to host elements?

Bind properties to host elements using @HostBinding:

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

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  @HostBinding('style.backgroundColor') backgroundColor = 'yellow';
}
            

975. How do you use Angular's `@HostListener` to listen to events from host elements?

Listen to events from host elements using @HostListener:

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

@Directive({
  selector: '[appClickTracker]'
})
export class ClickTrackerDirective {
  @HostListener('click', ['$event'])
  onClick(event: Event) {
    console.log('Element clicked:', event);
  }
}
            

976. How do you use Angular's `@ContentChildren` to access multiple projected content elements?

Access multiple projected content elements using @ContentChildren:

import { Component, ContentChildren, QueryList, AfterContentInit } from '@angular/core';
import { ChildComponent } from './child.component';

@Component({
  selector: 'app-parent',
  template: '<ng-content select="app-child"></ng-content>'
})
export class ParentComponent implements AfterContentInit {
  @ContentChildren(ChildComponent) contentChildren!: QueryList<ChildComponent>;

  ngAfterContentInit() {
    this.contentChildren.forEach(child => console.log('Projected child:', child));
  }
}
            

977. How do you use Angular's `@NgModule` to configure and provide global services?

Configure and provide global services using @NgModule:

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

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

 

Angular Advanced Level Questions - Part 17

978. How do you use Angular's `@Pipe` to create a custom pipe for formatting dates?

Create a custom date pipe:

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

@Pipe({
  name: 'customDate'
})
export class CustomDatePipe implements PipeTransform {
  transform(value: Date, format: string = 'MM/dd/yyyy'): string {
    const options: Intl.DateTimeFormatOptions = {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit'
    };
    return new Intl.DateTimeFormat('en-US', options).format(value);
  }
}
            

979. How do you use Angular's `@Injectable` to provide a service at a module level?

Provide a service at the module level:

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

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

980. How do you use Angular's `HttpClient` to perform HTTP requests with headers?

Perform HTTP requests with headers:

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class ApiService {
  constructor(private http: HttpClient) {}

  getData() {
    const headers = new HttpHeaders({
      'Authorization': 'Bearer your-token'
    });
    return this.http.get('/api/data', { headers });
  }
}
            

981. How do you use Angular's `Router` to handle route guards for authentication?

Handle route guards for authentication:

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

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(private router: Router) {}

  canActivate(): boolean {
    const isAuthenticated = false; // Replace with real authentication check
    if (!isAuthenticated) {
      this.router.navigate(['/login']);
      return false;
    }
    return true;
  }
}

const routes: Routes = [
  { path: 'protected', component: ProtectedComponent, canActivate: [AuthGuard] }
];
            

982. How do you use Angular's `@NgModule` to configure and provide global configurations?

Configure and provide global configurations:

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

export const API_CONFIG = new InjectionToken<string>('API_CONFIG');

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule],
  providers: [
    { provide: API_CONFIG, useValue: 'https://api.example.com' }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
            

983. How do you use Angular's `@NgModule` to define feature modules?

Define feature modules:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FeatureComponent } from './feature.component';

@NgModule({
  declarations: [FeatureComponent],
  imports: [CommonModule],
  exports: [FeatureComponent]
})
export class FeatureModule { }
            

984. How do you use Angular's `@NgModule` to import and configure third-party modules?

Import and configure third-party modules:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
import { ThirdPartyModule } from 'third-party-library';

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    HttpClientModule,
    ThirdPartyModule.forRoot({ apiKey: 'your-api-key' })
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
            

985. How do you use Angular's `@Component` to configure and manage component metadata?

Configure and manage component metadata:

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

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.css'],
  animations: [ /* animations here */ ]
})
export class ExampleComponent { }
            

986. How do you use Angular's `@NgModule` to define and use custom directives?

Define and use custom directives:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HighlightDirective } from './highlight.directive';

@NgModule({
  declarations: [HighlightDirective],
  imports: [CommonModule],
  exports: [HighlightDirective]
})
export class SharedModule { }

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

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  constructor(private el: ElementRef, private renderer: Renderer2) {
    this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow');
  }
}
            

987. How do you use Angular's `@NgModule` to configure and provide global services?

Configure and provide global services:

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

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

988. How do you use Angular's `@Component` to create and manage reusable components?

Create and manage reusable components:

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

@Component({
  selector: 'app-reusable',
  template: '<p>Hello, {{ name }}!</p>',
  styleUrls: ['./reusable.component.css']
})
export class ReusableComponent {
  @Input() name!: string;
}
            

989. How do you use Angular's `@Directive` to create custom behavior for DOM elements?

Create custom behavior for DOM elements:

import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';

@Directive({
  selector: '[appHover]'
})
export class HoverDirective {
  constructor(private el: ElementRef, private renderer: Renderer2) {}

  @HostListener('mouseenter') onMouseEnter() {
    this.renderer.setStyle(this.el.nativeElement, 'color', 'blue');
  }

  @HostListener('mouseleave') onMouseLeave() {
    this.renderer.setStyle(this.el.nativeElement, 'color', 'black');
  }
}
            

990. How do you use Angular's `@NgModule` to configure and provide routing modules?

Configure and provide routing modules:

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

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

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

991. How do you use Angular's `@Component` to manage component lifecycle hooks?

Manage component lifecycle hooks:

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

@Component({
  selector: 'app-lifecycle',
  template: '<p>Lifecycle Component</p>'
})
export class LifecycleComponent implements OnInit, OnDestroy {
  ngOnInit() {
    console.log('Component initialized');
  }

  ngOnDestroy() {
    console.log('Component destroyed');
  }
}
            

992. How do you use Angular's `@NgModule` to declare and use shared services?

Declare and use shared services:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SharedService } from './shared.service';

@NgModule({
  declarations: [],
  imports: [CommonModule],
  providers: [SharedService],
  exports: []
})
export class SharedModule { }
            

993. How do you use Angular's `@Injectable` to create and use services with different scopes?

Create and use services with different scopes:

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

@Injectable({
  providedIn: 'root' // Singleton service
})
export class SingletonService { }

@Injectable({
  providedIn: 'any' // Service available in any injector
})
export class ScopedService { }
            

994. How do you use Angular's `@NgModule` to configure and provide asynchronous modules?

Configure and provide asynchronous modules:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';
import { MyAsyncModule } from './my-async.module';

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

@NgModule({
  imports: [
    HttpClientModule
  ]
})
export class MyAsyncModule { }
            

995. How do you use Angular's `@NgModule` to provide global error handling?

Provide global error handling:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { ErrorHandler } from '@angular/core';
import { GlobalErrorHandler } from './global-error-handler';

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

996. How do you use Angular's `@NgModule` to configure and provide authentication services?

Configure and provide authentication services:

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

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

997. How do you use Angular's `@NgModule` to manage internationalization (i18n)?

Manage internationalization (i18n):

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { LOCALE_ID } from '@angular/core';
import { registerLocaleData } from '@angular/common';
import localeEs from '@angular/common/locales/es';

registerLocaleData(localeEs);

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule],
  providers: [{ provide: LOCALE_ID, useValue: 'es' }],
  bootstrap: [AppComponent]
})
export class AppModule { }
            

 

Angular Advanced Level Questions - Part 18

998. How do you use Angular's `@NgModule` to configure lazy loading of modules?

Configure lazy loading of modules:

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

const routes: Routes = [
  { path: '', component: HomeComponent },
  {
    path: 'feature',
    loadChildren: () => import('./feature/feature.module').then(m => m.FeatureModule)
  }
];

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

999. How do you use Angular's `@NgModule` to define and use feature modules?

Define and use feature modules:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FeatureComponent } from './feature.component';

@NgModule({
  declarations: [FeatureComponent],
  imports: [CommonModule],
  exports: [FeatureComponent]
})
export class FeatureModule { }
            

1000. How do you use Angular's `@Component` to handle complex data binding scenarios?

Handle complex data binding scenarios:

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

@Component({
  selector: 'app-complex-data',
  template: `
    <input [(ngModel)]="data.inputValue" />
    <button (click)="sendData()">Send</button>
  `,
  styleUrls: ['./complex-data.component.css']
})
export class ComplexDataComponent {
  @Input() data: any;
  @Output() dataChange = new EventEmitter<any>();

  sendData() {
    this.dataChange.emit(this.data);
  }
}
            

1001. How do you use Angular's `@Directive` to create a custom directive for form validation?

Create a custom directive for form validation:

import { Directive, Input } from '@angular/core';
import { NG_VALIDATORS, Validator, AbstractControl, ValidationErrors } from '@angular/forms';

@Directive({
  selector: '[appCustomValidator]',
  providers: [{ provide: NG_VALIDATORS, useExisting: CustomValidatorDirective, multi: true }]
})
export class CustomValidatorDirective implements Validator {
  @Input('appCustomValidator') forbiddenName: string;

  validate(control: AbstractControl): ValidationErrors | null {
    return control.value === this.forbiddenName ? { 'forbiddenName': true } : null;
  }
}
            

1002. How do you use Angular's `@Component` to manage nested components?

Manage nested components:

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

@Component({
  selector: 'app-parent',
  template: `
    <app-child [data]="parentData"></app-child>
  `
})
export class ParentComponent {
  parentData = 'Data from parent';
}

@Component({
  selector: 'app-child',
  template: '<p>{{ data }}</p>'
})
export class ChildComponent {
  @Input() data: string;
}
            

1003. How do you use Angular's `@NgModule` to provide global configuration settings?

Provide global configuration settings:

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

export const APP_CONFIG = new InjectionToken<string>('APP_CONFIG');

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule],
  providers: [
    { provide: APP_CONFIG, useValue: 'https://api.example.com' }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
            

1004. How do you use Angular's `@NgModule` to configure and use dependency injection in services?

Configure and use dependency injection in services:

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

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

1005. How do you use Angular's `@Component` to manage reactive forms with validation?

Manage reactive forms with validation:

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

@Component({
  selector: 'app-reactive-form',
  template: `
    <form [formGroup]="form" (ngSubmit)="onSubmit()">
      <input formControlName="name" />
      <div *ngIf="form.controls.name.invalid && form.controls.name.touched">
        Name is required
      </div>
      <button type="submit">Submit</button>
    </form>
  `
})
export class ReactiveFormComponent {
  form: FormGroup;

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

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

1006. How do you use Angular's `@Component` to handle component lifecycle hooks for optimizing performance?

Optimize performance using lifecycle hooks:

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

@Component({
  selector: 'app-optimization',
  template: '<p>Optimized Component</p>'
})
export class OptimizationComponent implements OnInit, OnDestroy {
  ngOnInit() {
    console.log('Component initialized');
    // Initialization code here
  }

  ngOnDestroy() {
    console.log('Component destroyed');
    // Cleanup code here
  }
}
            

1007. How do you use Angular's `@Directive` to create custom behavior for components?

Create custom behavior for components:

import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';

@Directive({
  selector: '[appCustomBehavior]'
})
export class CustomBehaviorDirective {
  constructor(private el: ElementRef, private renderer: Renderer2) {}

  @HostListener('click') onClick() {
    this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'blue');
  }
}
            

1008. How do you use Angular's `@NgModule` to configure and use HTTP interceptors?

Configure and use HTTP interceptors:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { AppComponent } from './app.component';
import { AuthInterceptor } from './auth.interceptor';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, HttpClientModule],
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
            

1009. How do you use Angular's `@NgModule` to configure and use Angular Elements?

Configure and use Angular Elements:

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

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule],
  entryComponents: [AppComponent]
})
export class AppModule {
  constructor(private injector: Injector) {
    const el = createCustomElement(AppComponent, { injector });
    customElements.define('my-element', el);
  }

  ngDoBootstrap() {}
}
            

1010. How do you use Angular's `@NgModule` to configure and use module lazy loading with `RouterModule`?

Configure and use module lazy loading with `RouterModule`:

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

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

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

1011. How do you use Angular's `@Component` to handle conditional rendering with `*ngIf`?

Handle conditional rendering with `*ngIf`:

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

@Component({
  selector: 'app-conditional',
  template: `
    <div *ngIf="showContent">
      Content is visible
    </div>
    <button (click)="toggleContent()">Toggle Content</button>
  `
})
export class ConditionalComponent {
  showContent = true;

  toggleContent() {
    this.showContent = !this.showContent;
  }
}
            

1012. How do you use Angular's `@Component` to handle dynamic component loading?

Handle dynamic component loading:

import { Component, ComponentFactoryResolver, ViewChild, ViewContainerRef } from '@angular/core';
import { DynamicComponent } from './dynamic.component';

@Component({
  selector: 'app-dynamic-loader',
  template: `
    <ng-template #container></ng-template>
    <button (click)="loadComponent()">Load Component</button>
  `
})
export class DynamicLoaderComponent {
  @ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef;

  constructor(private resolver: ComponentFactoryResolver) {}

  loadComponent() {
    const factory = this.resolver.resolveComponentFactory(DynamicComponent);
    this.container.createComponent(factory);
  }
}
            

1013. How do you use Angular's `@Component` to manage component interactions using `@Input` and `@Output`?

Manage component interactions using `@Input` and `@Output`:

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

@Component({
  selector: 'app-parent',
  template: `
    <app-child [data]="parentData" (dataChange)="onDataChange($event)"></app-child>
  `
})
export class ParentComponent {
  parentData = 'Data from parent';

  onDataChange(data: string) {
    console.log('Data from child:', data);
  }
}

@Component({
  selector: 'app-child',
  template: `
    <input [(ngModel)]="data" />
    <button (click)="sendData()">Send</button>
  `
})
export class ChildComponent {
  @Input() data: string;
  @Output() dataChange = new EventEmitter<string>();

  sendData() {
    this.dataChange.emit(this.data);
  }
}
            

1014. How do you use Angular's `@Component` to manage form controls with `FormArray`?

Manage form controls with `FormArray`:

import { Component } from '@angular/core';
import { FormBuilder, FormArray, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-form-array',
  template: `
    <form [formGroup]="form">
      <div formArrayName="items">
        <div *ngFor="let item of items.controls; let i = index">
          <input [formControlName]="i" />
        </div>
      </div>
      <button (click)="addItem()">Add Item</button>
    </form>
  `
})
export class FormArrayComponent {
  form: FormGroup;

  constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
      items: this.fb.array([this.fb.control('')])
    });
  }

  get items(): FormArray {
    return this.form.get('items') as FormArray;
  }

  addItem() {
    this.items.push(this.fb.control(''));
  }
}
            

1015. How do you use Angular's `@Component` to manage and handle HTTP requests with `HttpClient`?

Manage and handle HTTP requests with `HttpClient`:

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

@Component({
  selector: 'app-http',
  template: `
    <button (click)="fetchData()">Fetch Data</button>
    <p *ngIf="data">Data: {{ data | json }}</p>
  `
})
export class HttpComponent {
  data: any;

  constructor(private http: HttpClient) {}

  fetchData() {
    this.http.get('https://api.example.com/data').subscribe(response => {
      this.data = response;
    });
  }
}
            

1016. How do you use Angular's `@NgModule` to provide custom providers for dependency injection?

Provide custom providers for dependency injection:

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

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

1017. How do you use Angular's `@Component` to create a reusable modal component?

Create a reusable modal component:

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

@Component({
  selector: 'app-modal',
  template: `
    <div class="modal" *ngIf="isVisible">
      <div class="modal-content">
        <ng-content></ng-content>
        <button (click)="close()">Close</button>
      </div>
    </div>
  `,
  styles: [`
    .modal { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); display: flex; justify-content: center; align-items: center; }
    .modal-content { background: #fff; padding: 20px; border-radius: 5px; }
  `]
})
export class ModalComponent {
  isVisible = false;

  open() {
    this.isVisible = true;
  }

  close() {
    this.isVisible = false;
  }
}
            

 

Angular Advanced Level Questions - Part 19

1018. How do you use Angular's `@Component` to implement a custom validator for a form control?

Implement a custom validator for a form control:

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators, ValidatorFn, AbstractControl, ValidationErrors } from '@angular/forms';

@Component({
  selector: 'app-custom-validator',
  template: `
    <form [formGroup]="form">
      <input formControlName="username" />
      <div *ngIf="form.get('username').hasError('customError')">Custom error message</div>
    </form>
  `
})
export class CustomValidatorComponent {
  form: FormGroup;

  constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
      username: ['', [this.customValidator()]]
    });
  }

  customValidator(): ValidatorFn {
    return (control: AbstractControl): ValidationErrors | null => {
      const isValid = /^[a-zA-Z0-9_]+$/.test(control.value);
      return isValid ? null : { customError: true };
    };
  }
}
            

1019. How do you use Angular's `@NgModule` to configure an Angular application with Angular Universal for server-side rendering?

Configure an Angular application with Angular Universal:

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

@NgModule({
  imports: [
    BrowserModule.withServerTransition({ appId: 'my-app' }),
    AppServerModule
  ],
  declarations: [AppComponent],
  bootstrap: [AppComponent]
})
export class AppModule { }
            

1020. How do you use Angular's `@Component` to create a directive that modifies the host element's style?

Create a directive that modifies the host element's style:

import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  constructor(private el: ElementRef, private renderer: Renderer2) {}

  @HostListener('mouseenter') onMouseEnter() {
    this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow');
  }

  @HostListener('mouseleave') onMouseLeave() {
    this.renderer.removeStyle(this.el.nativeElement, 'backgroundColor');
  }
}
            

1021. How do you use Angular's `@Component` to handle the lifecycle of a component with `ngOnInit` and `ngOnDestroy`?

Handle the lifecycle of a component with `ngOnInit` and `ngOnDestroy`:

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

@Component({
  selector: 'app-lifecycle',
  template: `
    <p>Component Lifecycle</p>
  `
})
export class LifecycleComponent implements OnInit, OnDestroy {

  ngOnInit() {
    console.log('Component Initialized');
  }

  ngOnDestroy() {
    console.log('Component Destroyed');
  }
}
            

1022. How do you use Angular's `@NgModule` to create a feature module with its own routes?

Create a feature module with its own routes:

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

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

@NgModule({
  imports: [RouterModule.forChild(routes)],
  declarations: [FeatureComponent]
})
export class FeatureModule { }
            

1023. How do you use Angular's `@NgModule` to configure HTTP client interceptors?

Configure HTTP client interceptors:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { AppComponent } from './app.component';
import { AuthInterceptor } from './auth.interceptor';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, HttpClientModule],
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
            

1024. How do you use Angular's `@Component` to implement a form with nested form groups?

Implement a form with nested form groups:

import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-nested-form',
  template: `
    <form [formGroup]="form">
      <div formGroupName="address">
        <input formControlName="street" />
        <input formControlName="city" />
      </div>
      <button (click)="submit()">Submit</button>
    </form>
  `
})
export class NestedFormComponent {
  form: FormGroup;

  constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
      address: this.fb.group({
        street: [''],
        city: ['']
      })
    });
  }

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

1025. How do you use Angular's `@Component` to create a component that uses Angular's content projection with `ng-content`?

Create a component that uses content projection:

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

@Component({
  selector: 'app-wrapper',
  template: `
    <div class="wrapper">
      <ng-content></ng-content>
    </div>
  `,
  styles: [`
    .wrapper { border: 1px solid #ccc; padding: 10px; }
  `]
})
export class WrapperComponent {}
            

1026. How do you use Angular's `@Component` to manage component interactions using Angular Services?

Manage component interactions using Angular Services:

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

@Injectable({
  providedIn: 'root'
})
export class DataService {
  private dataSubject = new BehaviorSubject<string>('Initial Data');
  data$ = this.dataSubject.asObservable();

  updateData(newData: string) {
    this.dataSubject.next(newData);
  }
}

import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service';

@Component({
  selector: 'app-consumer',
  template: `
    <p>Data: {{ data }}</p>
    <button (click)="changeData()">Change Data</button>
  `
})
export class ConsumerComponent implements OnInit {
  data: string;

  constructor(private dataService: DataService) {}

  ngOnInit() {
    this.dataService.data$.subscribe(data => this.data = data);
  }

  changeData() {
    this.dataService.updateData('New Data');
  }
}
            

1027. How do you use Angular's `@NgModule` to configure lazy loading of feature modules?

Configure lazy loading of feature modules:

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

const routes: Routes = [
  { path: '', component: MainComponent },
  { path: 'feature', loadChildren: () => import('./feature/feature.module').then(m => m.FeatureModule) }
];

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

1028. How do you use Angular's `@NgModule` to set up a module with providers for different environments?

Set up a module with providers for different environments:

import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { environment } from '../environments/environment';

@NgModule({
  imports: [HttpClientModule],
  providers: [
    { provide: 'API_URL', useValue: environment.apiUrl }
  ]
})
export class AppModule { }
            

1029. How do you use Angular's `@Component` to create a reusable dialog component?

Create a reusable dialog component:

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

@Component({
  selector: 'app-dialog',
  template: `
    <div class="dialog">
      <div class="dialog-content">
        <ng-content></ng-content>
      </div>
    </div>
  `,
  styles: [`
    .dialog { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); display: flex; justify-content: center; align-items: center; }
    .dialog-content { background: #fff; padding: 20px; border-radius: 5px; }
  `]
})
export class DialogComponent {}
            

1030. How do you use Angular's `@Component` to implement a dynamic component loader?

Implement a dynamic component loader:

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

@Component({
  selector: 'app-dynamic-loader',
  template: `
    <ng-template #dynamicContainer></ng-template>
  `
})
export class DynamicLoaderComponent implements OnInit {
  @ViewChild('dynamicContainer', { read: ViewContainerRef }) container: ViewContainerRef;

  constructor(private componentFactoryResolver: ComponentFactoryResolver) {}

  ngOnInit() {
    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(SomeDynamicComponent);
    this.container.createComponent(componentFactory);
  }
}
            

1031. How do you use Angular's `@Component` to manage animations with Angular's animation library?

Manage animations with Angular's animation library:

import { Component } from '@angular/core';
import { trigger, state, style, transition, animate } from '@angular/animations';

@Component({
  selector: 'app-animated',
  template: `
    <div [@fadeInOut]="state" (click)="toggle()">Click me to toggle animation</div>
  `,
  animations: [
    trigger('fadeInOut', [
      state('in', style({ opacity: 1 })),
      state('out', style({ opacity: 0 })),
      transition('in <=> out', [animate('0.5s')])
    ])
  ]
})
export class AnimatedComponent {
  state = 'in';

  toggle() {
    this.state = this.state === 'in' ? 'out' : 'in';
  }
}
            

1032. How do you use Angular's `@NgModule` to provide configuration settings for a specific environment?

Provide configuration settings for a specific environment:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HttpClientModule } from '@angular/common/http';
import { environment } from '../environments/environment';

@NgModule({
  imports: [CommonModule, HttpClientModule],
  providers: [
    { provide: 'API_URL', useValue: environment.apiUrl }
  ]
})
export class AppModule { }
            

1033. How do you use Angular's `@Component` to manage form validation with asynchronous validators?

Manage form validation with asynchronous validators:

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, AsyncValidatorFn, AbstractControl, ValidationErrors } from '@angular/forms';
import { Observable, of } from 'rxjs';
import { debounceTime, map, catchError } from 'rxjs/operators';

@Component({
  selector: 'app-async-validator',
  template: `
    <form [formGroup]="form">
      <input formControlName="username" />
      <div *ngIf="form.get('username').hasError('asyncError')">Username is already taken</div>
    </form>
  `
})
export class AsyncValidatorComponent {
  form: FormGroup;

  constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
      username: ['', [], [this.asyncValidator()]]
    });
  }

  asyncValidator(): AsyncValidatorFn {
    return (control: AbstractControl): Observable<ValidationErrors | null> => {
      return of(control.value).pipe(
        debounceTime(300),
        map(value => value === 'admin' ? { asyncError: true } : null),
        catchError(() => of(null))
      );
    };
  }
}
            

1034. How do you use Angular's `@Component` to implement a custom pipe for transforming data?

Implement a custom pipe for transforming data:

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

@Pipe({
  name: 'reverse'
})
export class ReversePipe implements PipeTransform {
  transform(value: string): string {
    return value.split('').reverse().join('');
  }
}
            

1035. How do you use Angular's `@Component` to handle route guards for protecting routes?

Handle route guards for protecting routes:

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {

  constructor(private router: Router) {}

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): boolean {
    const isAuthenticated = false; // Check authentication logic
    if (!isAuthenticated) {
      this.router.navigate(['/login']);
      return false;
    }
    return true;
  }
}
            

1036. How do you use Angular's `@Component` to create a component that listens to events from a child component?

Create a component that listens to events from a child component:

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

@Component({
  selector: 'app-child',
  template: `<button (click)="notifyParent()">Notify</button>`
})
export class ChildComponent {
  @Output() notify: EventEmitter<void> = new EventEmitter<void>();

  notifyParent() {
    this.notify.emit();
  }
}

@Component({
  selector: 'app-parent',
  template: `
    <app-child (notify)="onNotify()"></app-child>
  `
})
export class ParentComponent {
  onNotify() {
    console.log('Child component event received');
  }
}
            

1037. How do you use Angular's `@Component` to implement dependency injection for services?

Implement dependency injection for services:

import { Component } from '@angular/core';
import { DataService } from './data.service';

@Component({
  selector: 'app-example',
  template: `<div>Data: {{ data }}</div>`,
  providers: [DataService]
})
export class ExampleComponent {
  data: string;

  constructor(private dataService: DataService) {
    this.data = this.dataService.getData();
  }
}
            

 

Angular Advanced Level Questions - Part 20

1038. How do you use Angular's `@NgModule` to configure feature modules with lazy loading and preloading strategies?

Configure feature modules with lazy loading and preloading strategies:

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

const routes: Routes = [
  { path: '', component: MainComponent },
  { path: 'feature', loadChildren: () => import('./feature/feature.module').then(m => m.FeatureModule) }
];

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

1039. How do you use Angular's `@NgModule` to configure dependency injection for a multi-provider scenario?

Configure dependency injection for a multi-provider scenario:

import { NgModule } from '@angular/core';
import { SomeService } from './some.service';
import { AnotherService } from './another.service';

@NgModule({
  providers: [
    { provide: SomeService, useClass: AnotherService, multi: true }
  ]
})
export class AppModule { }
            

1040. How do you implement Angular's `@Component` to support dynamic content projection with multiple slots?

Implement dynamic content projection with multiple slots:

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

@Component({
  selector: 'app-multi-slot',
  template: `
    <ng-content select="[header]"></ng-content>
    <div class="body"><ng-content></ng-content></div>
    <ng-content select="[footer]"></ng-content>
  `,
  styles: [`
    .body { padding: 10px; }
  `]
})
export class MultiSlotComponent { }
            

1041. How do you use Angular's `@Component` to manage and bind data to a table with sorting and filtering functionality?

Manage and bind data to a table with sorting and filtering:

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

@Component({
  selector: 'app-table',
  template: `
    <input [formControl]="filterControl" placeholder="Filter">
    <table>
      <thead>
        <tr>
          <th>Name</th>
          <th>Age</th>
        </tr>
      </thead>
      <tbody>
        <tr *ngFor="let item of filteredItems">
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
        </tr>
      </tbody>
    </table>
  `
})
export class TableComponent {
  filterControl = new FormControl('');
  items = [{ name: 'Alice', age: 30 }, { name: 'Bob', age: 25 }];
  filteredItems = this.items;

  constructor() {
    this.filterControl.valueChanges.subscribe(filterText => {
      this.filteredItems = this.items.filter(item => item.name.includes(filterText));
    });
  }
}
            

1042. How do you use Angular's `@Component` to create a component that handles file uploads?

Create a component that handles file uploads:

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

@Component({
  selector: 'app-file-upload',
  template: `
    <input type="file" (change)="onFileChange($event)" />
  `
})
export class FileUploadComponent {
  onFileChange(event) {
    const file = event.target.files[0];
    if (file) {
      console.log('Selected file:', file);
    }
  }
}
            

1043. How do you use Angular's `@Component` to manage state with a Redux-like pattern?

Manage state with a Redux-like pattern:

import { Component } from '@angular/core';
import { Store, Select } from '@ngxs/store';
import { Observable } from 'rxjs';
import { Increment } from './counter.actions';
import { CounterState } from './counter.state';

@Component({
  selector: 'app-counter',
  template: `
    <button (click)="increment()">Increment</button>
    <p>Count: {{ count$ | async }}</p>
  `
})
export class CounterComponent {
  @Select(CounterState.getCount) count$: Observable<number>;

  constructor(private store: Store) {}

  increment() {
    this.store.dispatch(new Increment());
  }
}
            

1044. How do you use Angular's `@NgModule` to configure multiple routers for different feature modules?

Configure multiple routers for different feature modules:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { Feature1Component } from './feature1.component';
import { Feature2Component } from './feature2.component';

const feature1Routes: Routes = [
  { path: 'feature1', component: Feature1Component }
];

const feature2Routes: Routes = [
  { path: 'feature2', component: Feature2Component }
];

@NgModule({
  imports: [
    RouterModule.forChild(feature1Routes),
    RouterModule.forChild(feature2Routes)
  ],
  exports: [RouterModule]
})
export class FeatureRoutingModule { }
            

1045. How do you use Angular's `@Component` to create a custom directive for toggling visibility?

Create a custom directive for toggling visibility:

import { Directive, ElementRef, Input, Renderer2 } from '@angular/core';

@Directive({
  selector: '[appToggleVisibility]'
})
export class ToggleVisibilityDirective {
  @Input() set appToggleVisibility(visible: boolean) {
    this.renderer.setStyle(this.el.nativeElement, 'display', visible ? 'block' : 'none');
  }

  constructor(private el: ElementRef, private renderer: Renderer2) {}
}
            

1046. How do you use Angular's `@Component` to integrate with external libraries or APIs?

Integrate with external libraries or APIs:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-external-api',
  template: `
    <div *ngIf="data">
      <p>Data from API: {{ data | json }}</p>
    </div>
  `
})
export class ExternalApiComponent implements OnInit {
  data: any;

  constructor(private http: HttpClient) {}

  ngOnInit() {
    this.http.get('https://api.example.com/data')
      .subscribe(response => this.data = response);
  }
}
            

1047. How do you use Angular's `@Component` to manage form validation with reactive forms?

Manage form validation with reactive forms:

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

@Component({
  selector: 'app-reactive-form',
  template: `
    <form [formGroup]="form" (ngSubmit)="onSubmit()">
      <input formControlName="name" placeholder="Name" />
      <div *ngIf="form.get('name').invalid && form.get('name').touched">
        Name is required
      </div>
      <button type="submit" [disabled]="form.invalid">Submit</button>
    </form>
  `
})
export class ReactiveFormComponent {
  form: FormGroup;

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

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

1048. How do you use Angular's `@Component` to create a custom pipe for transforming data?

Create a custom pipe for transforming data:

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

@Pipe({
  name: 'reverse'
})
export class ReversePipe implements PipeTransform {
  transform(value: string): string {
    return value.split('').reverse().join('');
  }
}
            

1049. How do you use Angular's `@NgModule` to configure routes with child routes and route guards?

Configure routes with child routes and route guards:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { ParentComponent } from './parent.component';
import { ChildComponent } from './child.component';
import { AuthGuard } from './auth.guard';

const routes: Routes = [
  {
    path: 'parent',
    component: ParentComponent,
    canActivate: [AuthGuard],
    children: [
      { path: 'child', component: ChildComponent }
    ]
  }
];

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

1050. How do you use Angular's `@Component` to implement advanced animations with `@angular/animations`?

Implement advanced animations with `@angular/animations`:

import { Component } from '@angular/core';
import { trigger, transition, style, animate } from '@angular/animations';

@Component({
  selector: 'app-animate',
  template: `
    <div [@fadeInOut]="state">Content</div>
    <button (click)="toggle()">Toggle</button>
  `,
  animations: [
    trigger('fadeInOut', [
      transition(':enter', [
        style({ opacity: 0 }),
        animate('500ms', style({ opacity: 1 }))
      ]),
      transition(':leave', [
        animate('500ms', style({ opacity: 0 }))
      ])
    ])
  ]
})
export class AnimateComponent {
  state = 'visible';

  toggle() {
    this.state = this.state === 'visible' ? 'hidden' : 'visible';
  }
}
            

1051. How do you use Angular's `@NgModule` to configure dynamic module loading and module federation?

Configure dynamic module loading and module federation:

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

const routes: Routes = [
  { path: '', component: MainComponent },
  { path: 'dynamic', loadChildren: () => import('./dynamic/dynamic.module').then(m => m.DynamicModule) }
];

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

1052. How do you use Angular's `@Component` to handle internationalization (i18n) for multilingual applications?

Handle internationalization (i18n) for multilingual applications:

import { Component } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';

@Component({
  selector: 'app-i18n',
  template: `
    <div>
      <p>{{ 'WELCOME_MESSAGE' | translate }}</p>
      <button (click)="switchLanguage('en')">English</button>
      <button (click)="switchLanguage('es')">Español</button>
    </div>
  `
})
export class I18nComponent {
  constructor(private translate: TranslateService) {
    translate.setDefaultLang('en');
  }

  switchLanguage(lang: string) {
    this.translate.use(lang);
  }
}
            

1053. How do you use Angular's `@Component` to implement a custom form control with `ControlValueAccessor`?

Implement a custom form control with `ControlValueAccessor`:

import { Component, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

@Component({
  selector: 'app-custom-input',
  template: `
    <input [value]="value" (input)="onChange($event.target.value)" />
  `,
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => CustomInputComponent),
      multi: true
    }
  ]
})
export class CustomInputComponent implements ControlValueAccessor {
  value: any;
  onChange = (value: any) => {};
  onTouched = () => {};

  writeValue(value: any): void {
    this.value = value;
  }

  registerOnChange(fn: (value: any) => void): void {
    this.onChange = fn;
  }

  registerOnTouched(fn: () => void): void {
    this.onTouched = fn;
  }

  setDisabledState?(isDisabled: boolean): void {}
}
            

1054. How do you use Angular's `@NgModule` to integrate with third-party libraries and configure their modules?

Integrate with third-party libraries and configure their modules:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { SomeThirdPartyModule } from 'some-third-party-library';

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

1055. How do you use Angular's `@Component` to implement a component with custom input decorators and property bindings?

Implement a component with custom input decorators and property bindings:

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

@Component({
  selector: 'app-custom-input',
  template: `
    <div>
      <p>Input value: {{ value }}</p>
      <button (click)="notify.emit(value)">Notify</button>
    </div>
  `
})
export class CustomInputComponent {
  @Input() value: string;
  @Output() notify = new EventEmitter<string>();
}
            

1056. How do you use Angular's `@Component` to create a component that interacts with a WebSocket service?

Create a component that interacts with a WebSocket service:

import { Component, OnInit, OnDestroy } from '@angular/core';
import { WebSocketService } from './web-socket.service';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-web-socket',
  template: `
    <div>
      <p>WebSocket Data: {{ data }}</p>
    </div>
  `
})
export class WebSocketComponent implements OnInit, OnDestroy {
  data: string;
  private subscription: Subscription;

  constructor(private webSocketService: WebSocketService) {}

  ngOnInit() {
    this.subscription = this.webSocketService.getData().subscribe(data => {
      this.data = data;
    });
  }

  ngOnDestroy() {
    if (this.subscription) {
      this.subscription.unsubscribe();
    }
  }
}
            

1057. How do you use Angular's `@Component` to handle dynamic component loading and rendering?

Handle dynamic component loading and rendering:

import { Component, ViewContainerRef, ComponentFactoryResolver, OnInit } from '@angular/core';
import { DynamicComponent } from './dynamic.component';

@Component({
  selector: 'app-dynamic-loader',
  template: `
    <ng-template #dynamicContainer></ng-template>
    <button (click)="loadComponent()">Load Dynamic Component</button>
  `
})
export class DynamicLoaderComponent implements OnInit {
  @ViewChild('dynamicContainer', { read: ViewContainerRef }) container: ViewContainerRef;

  constructor(private resolver: ComponentFactoryResolver) {}

  ngOnInit() {}

  loadComponent() {
    const factory = this.resolver.resolveComponentFactory(DynamicComponent);
    this.container.clear();
    this.container.createComponent(factory);
  }
}
            

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

1058. OnPush child ignores an in-place mutation of an @Input object

A parent passes user to an OnPush child, then mutates user.name without replacing the object reference. The child view stays stale. What is the root cause, and what is the smallest correct fix that preserves OnPush semantics?

<app-profile [user]=\"user\"></app-profile>

// parent
this.user.name = 'Ada';
// child is OnPush

1059. Zoneless Angular: a third-party callback updates data but the view does not refresh

In an Angular 18 zoneless application, a non-Angular library invokes a callback after an HTTP response. The component state changes, but the template is not updated until another interaction occurs. Which APIs can explicitly schedule change detection in zoneless mode, what common Zone.js assumption is being violated, and how would you redesign this flow with signals?

lib.onResult((result) => {
  this.result = result; // no view update
});

1060. Migrating *ngFor trackBy to @for track: why is tracking by index dangerous?

A large list is migrated from *ngFor="let item of items; trackBy: trackById" to @for (item of items; track item.id). A teammate proposes track $index for simplicity. In what reordering, insertion, or deletion scenarios does index tracking cause incorrect DOM reuse, stale component state, and accessibility/focus bugs? What identity rule should govern the track expression?

1061. CDK virtual scrolling with variable-height items and blank gaps

An <cdk-virtual-scroll-viewport> uses a fixed size strategy, but list items have variable heights. During fast scrolling, users see blank gaps, incorrect total scroll height, and recycled rows retaining stale content. What are the likely measurement and recycling causes, which CDK strategies or configuration changes address variable heights, and what constraints remain for very dynamic content?

<cdk-virtual-scroll-viewport itemSize=\"48\">
  <div *cdkVirtualFor=\"let item of items\">{{ item.text }}</div>
</cdk-virtual-scroll-viewport>

1062. Pure pipe memoization: why does a mutated array not update the view?

A pure pipe transforms an array and appears to cache its result. After items.push(newItem), the pipe is not called again and the template remains stale. Why does Angular's pure-pipe memoization behave this way, and what are the correct fixes for mutable data without making the pipe impure?

@Pipe({ name: 'sum', pure: true })
export class SumPipe implements PipeTransform {
  transform(values: number[]): number {
    return values.reduce((a, b) => a + b, 0);
  }
}

1063. Signal computed memoization and custom equality

A computed() signal depends on an object signal. The object is replaced with a new object whose nested values are deeply equal, but the computed unexpectedly recomputes, or in another variant it fails to recompute when an equal-by-reference object is mutated. How does Angular's default equality check work for signals and computed values, how can equality be customized, and what are the risks of using deep equality in hot change-detection paths?

const user = signal({ name: 'Ada' });
const label = computed(() => `User: ${user().name}`);

1064. Profiling an Angular app where change detection runs far too often

Angular DevTools shows a component being checked on every mouse move, even when its inputs are unchanged and it is OnPush. The profiler flame chart points to a parent with a method call in its template. How do you distinguish Zone-triggered checks from signal/template-expression checks, which tools and APIs can measure change-detection cost, and what refactoring steps reduce checks without changing user-visible behavior?

<p>{{ expensiveLabel() }}</p>
<app-child [data]=\"data\"></app-child>

1065. Memory leak from an unmanaged RxJS subscription in a component

A component subscribes to a long-lived service observable in ngOnInit but never unsubscribes. After navigation, memory grows and callbacks continue firing. Identify the leak, explain why ngOnDestroy omission is not the only issue, and compare fixes using takeUntilDestroyed, DestroyRef, and the async pipe.

ngOnInit() {
  this.service.events$.subscribe(event => {
    this.latest = event;
  });
}

1066. Dynamic component creation leaks detached views and listeners

Components are repeatedly created with ViewContainerRef.createComponent or ComponentRef, but old instances are only removed from the DOM, not destroyed. Event listeners, subscriptions, and DOM nodes remain. What cleanup invariants must hold, how should creation and destruction be paired, and what role do ComponentRef.destroy(), view detachment, and DestroyRef play?

const ref = this.vcr.createComponent(MyComponent);
// later: ref.location.nativeElement.remove();

1067. Large-list rendering strategy: @defer, track, OnPush, and initial paint

A page renders 10,000 rows with nested child components. The team wants to avoid blocking initial paint while keeping updates efficient. How would you combine @defer triggers, stable track identity, OnPush boundaries, virtual scrolling, and pure pipes to minimize main-thread work, and what correctness risks arise from deferred hydration or delayed list measurement?

@defer (on viewport) {
  @for (row of rows; track row.id) {
    <app-row [row]=\"row\" />
  }
}

1068. A component renders {{ new Date().toISOString() }} directly in its template. During SSR the server renders one timestamp, but hydration on the client expects a different value, producing a hydration mismatch. What is the most robust fix that preserves SSR output while keeping the value reactive on the client?

Explain why calling Date.now() during render is non-deterministic across server/client, and describe an approach using a signal initialized in afterNextRender (or ngAfterViewInit guarded by isPlatformBrowser) plus a stable placeholder, including how TransferState could carry the server value if it must be shared.

1069. During hydration, a user clicks a button before Angular finishes hydrating the view. The click appears lost because the DOM node is not yet interactive. How does Angular's event replay mechanism handle this, and what constraints apply to which events are replayed and in what order?

Discuss the event replay queue, how replayed events are dispatched after hydration completes, ordering guarantees, limitations with non-bubbling or custom events, and how provideClientHydration(withEventReplay()) enables this behavior.

1070. You use @defer (on viewport) around a heavy chart component in an SSR app. Explain how deferrable views interact with server rendering and hydration: what gets rendered on the server, what is deferred on the client, and how placeholders/triggers affect hydration boundaries and layout shift.

Cover server-side rendering of the placeholder vs. deferred content, client-side trigger evaluation, hydration of the deferred block, and pitfalls like hydration mismatches when the placeholder differs between server and client.

1071. Partial/incremental hydration allows hydrating only parts of the application. Describe a scenario where you would hydrate a sidebar lazily while keeping the main content static, and explain the APIs and configuration involved, including how hydration boundaries and ngSkipHydration interact.

Explain incremental hydration concepts, deferrable view integration, boundary marking, and when skipping hydration is appropriate versus harmful.

1072. An SSR app makes an HTTP request during rendering and the client repeats the same request after hydration, causing a flash and duplicate network calls. How does TransferState solve this, and what are the common pitfalls when using makeStateKey and get/set?

Describe server-side state serialization into the HTML, client-side consumption during hydration, key naming collisions, type safety, and cleanup. Include an example pattern with an HTTP interceptor or service.

1073. A developer uses window.localStorage directly inside a component constructor. This throws during SSR. Compare the correct platform-guarded approaches using isPlatformBrowser, isPlatformServer, and Angular's PLATFORM_ID injection, including where each check should live.

Discuss constructor vs. lifecycle hook placement, effects, and why platform checks should be minimized in favor of browser-only lifecycle hooks.

1074. You need to manipulate the DOM (focus an input) only in the browser after the view renders. Compare afterNextRender, afterRender, and ngAfterViewInit for this task in an SSR/hydrated app, including execution timing relative to hydration and repeated invocations.

Explain when each runs, cleanup considerations, and why afterNextRender is preferred for one-off browser-only DOM work.

1075. A component uses a third-party library that accesses document at import time. This breaks SSR. Outline strategies to isolate browser-only code, such as dynamic imports, isPlatformBrowser guards, lazy loading, and providing a no-op server implementation, with trade-offs.

Include module-level side effects, tree-shaking implications, and how to keep the server bundle clean.

1076. Hydration fails because the server-rendered DOM contains an extra wrapper element not present in the client template (e.g., from a directive or conditional). How do you diagnose and fix hydration mismatches, and what role does ngSkipHydration play as a last resort?

Discuss Angular hydration error messages, DOM comparison, common causes (whitespace, i18n, directives), and the cost of skipping hydration on a subtree.

1077. In an app using provideClientHydration(), a route guard or resolver runs browser-only APIs during SSR. Explain how to structure resolvers/guards to be platform-safe, how to defer browser-dependent logic, and how to avoid hydration mismatches caused by route-level state differences.

Cover injection of PLATFORM_ID, server-compatible defaults, and transferring resolved state via TransferState.

1078. How does createEntityAdapter's selectId and sortComparer shape a normalized cache, and what pitfalls arise when denormalized updates touch nested relations?

const adapter = createEntityAdapter<User>({
  selectId: (u) => u.id,
  sortComparer: (a, b) => a.lastName.localeCompare(b.lastName)
});
const initialState = adapter.getInitialState({ loading: false });
// updateOne replaces the entity reference; derived collections must be recomputed via selectors

1079. Why does a selector that returns a new object or array on every evaluation defeat memoization, and how should createSelector and createFeatureSelector be composed?

const selectUserState = createFeatureSelector<UserState>('users');
const selectUserIds = createSelector(selectUserState, (s) => s.ids); // stable reference
const selectSortedUsers = createSelector(selectUserIds, selectUserEntities, (ids, entities) =>
  ids.map((id) => entities[id]).filter(Boolean)
);

1080. When should an NgRx effect use switchMap, mergeMap, concatMap, or exhaustMap, and how do these operators prevent or permit race conditions?

search$ = createEffect(() =>
  this.actions$.pipe(
    ofType(UserActions.search),
    switchMap(({ query }) => this.api.search(query).pipe(
      map((results) => UserActions.searchSuccess({ results })),
      catchError((error) => of(UserActions.searchFailure({ error })))
    ))
  )
);

1081. How can optimistic updates be implemented in NgRx with deterministic rollback, including correlation IDs and failure-aware action metadata?

this.store.dispatch(UserActions.updateOptimistic({
  id: user.id,
  changes: { name: 'New' },
  correlationId: crypto.randomUUID()
}));
// On failure, dispatch a rollback action keyed by correlationId and rehydrate from server state

1082. How should feature stores, shared state, and reducer composition be wired with provideStore and provideEffects while avoiding circular dependencies?

export const appConfig = [
  provideStore({ router: routerReducer, shared: sharedReducer }),
  provideEffects([SharedEffects, UserEffects]),
  provideState(usersFeature)
];
// Feature reducers should depend only on their slice and shared selectors, never import another feature's reducer directly

1083. Computed signals: when does a derived value actually recompute?

In an advanced NgRx SignalStore, you define a computed signal that reads several source signals and performs an expensive transformation. A teammate claims the computed re-evaluates on every change-detection cycle regardless of inputs. Is that correct, and how would you force it to skip recomputation when a derived primitive (e.g. a filtered list length) is unchanged but the underlying array reference changed?

const store = signalStore(
  { providedIn: 'root' },
  withState({ items: [] as Item[] }),
  withComputed(({ items }) => ({
    activeCount: computed(() => items().filter(i => i.active).length, {
      equal: (a, b) => a === b,
    }),
  }))
);

Explain the caching/memoization contract of computed(), what equal controls vs. what it cannot prevent, and one pattern to avoid recomputing when only an irrelevant property of an item changes.

1084. rxMethod: cancellation, ordering, and error containment

You expose an rxMethod that calls a search API on every keystroke. Under rapid input, stale responses overwrite fresh ones. Which RxJS operator should wrap the inner observable to guarantee only the latest request wins, and how do you keep a thrown HTTP error from terminating the outer method stream? Show the corrected shape.

rxMethod<string>((query$) =>
  query$.pipe(
    debounceTime(300),
    distinctUntilChanged(),
    switchMap(q => this.http.get<Result[]>(`/api/search?q=${q}`)),
    tapResponse({
      next: (results) => patchState(store, { results }),
      error: (err) => patchState(store, { error: err as Error }),
    })
  )
);

Discuss the difference between switchMap, exhaustMap, and concatMap here, and why tapResponse (from @ngrx/operators) is preferred over a plain tap + catchError for store methods.

1085. DevTools: time-travel and computed state

With @ngrx/store-devtools wired into a SignalStore via withDevtools('feature'), you jump back to an earlier snapshot. Computed signals and effects that derived from the jumped state appear stale. What are the inherent limitations of time-travel with signal-based stores, and which state changes are NOT captured by DevTools snapshots (effects, computed, non-serializable values)? Provide a debugging checklist.

const store = signalStore(
  { providedIn: 'root' },
  withState({ count: 0 }),
  withComputed(({ count }) => ({ doubled: computed(() => count() * 2) })),
  withMethods((store) => ({
    increment: () => patchState(store, (s) => ({ count: s.count + 1 })),
  })),
  withDevtools('counter')
);

Explain why computed values are recomputed (not restored) on jump, and how to keep DevTools payloads serializable and small.

1086. Cross-store composition without circular injection

Store B needs to react to Store A's state, and Store A needs to call a method on Store B. Directly injecting each store into the other's factory causes a circular dependency. Describe two safe composition patterns (facade/service mediator, and event-driven via a shared subject or SignalStore feature) and when to prefer each. Include a minimal code sketch for the mediator approach.

// Unsafe: circular
export const StoreA = signalStore(
  withMethods((a, b = inject(StoreB)) => ({ ... }))
);
export const StoreB = signalStore(
  withMethods((b, a = inject(StoreA)) => ({ ... }))
);

Explain how inject() inside withMethods interacts with Angular's DI, and why moving shared logic into a plain injectable service avoids the cycle.

1087. Testing SignalStore: mocking, async methods, and change detection

In a Jest/Karma test you want to verify that an rxMethod updates state after a mocked HTTP call resolves. Using TestBed.configureTestingModule, how do you provide a store instance (or override its dependencies), flush microtasks/timers, and assert on signal values without triggering real change detection? Provide a robust test skeleton and list common pitfalls (zoneless, fakeAsync vs. rxjs TestScheduler, and over-mocking the store).

TestBed.configureTestingModule({
  providers: [
    provideHttpClient(),
    provideHttpClientTesting(),
    // TODO: provide store + mock dependency
  ],
});
const store = TestBed.inject(MyStore);
const httpMock = TestBed.inject(HttpTestingController);

Explain when to use fakeAsync + tick() versus flushMicrotasks(), and how to assert computed signals derived from patched state.

1088. How does Angular's DomSanitizer classify values into trusted/untrusted contexts, and what concrete risks arise when you call bypassSecurityTrustHtml() on attacker-controlled data?

DomSanitizer tracks a value's security context (HTML, STYLE, SCRIPT, URL, RESOURCE_URL) separately from its raw string. Built-in sanitization strips dangerous constructs (e.g., <script>, event handlers, javascript: URLs) per context. Calling bypassSecurityTrustHtml() marks the value as trusted for that context and disables all sanitization, so any XSS payload flows straight into the DOM via [innerHTML]. The advanced pitfall is that "trusted" is a developer assertion, not a runtime check: if the input is derived from query params, route data, or stored user content, you have introduced a stored/reflected XSS. Prefer structural binding, keep sanitization on, and reserve bypass* for compile-time constants or server-signed fragments.

// UNSAFE: user input bypasses sanitization
this.html = this.sanitizer.bypassSecurityTrustHtml(this.route.snapshot.queryParamMap.get('msg')!);

// SAFE: sanitize explicitly, or bind textually
this.html = this.sanitizer.sanitize(SecurityContext.HTML, untrusted) ?? '';

1089. What is the difference between Angular's built-in sanitization and the Trusted Types API, and how do you wire a Trusted Types policy to satisfy a strict CSP with require-trusted-types-for 'script'?

Angular sanitizes values before DOM insertion, but CSP Trusted Types moves enforcement to the browser: any sink assignment (innerHTML, eval, etc.) must receive a TrustedHTML/TrustedScript object created by a registered policy. Angular ships a default policy name angular when trustedTypes is enabled, but custom directives or third-party libs may create their own sinks. To comply you must register a policy whose createHTML applies your allow-list, and ensure every code path that touches sinks goes through it. Mismatches surface as runtime TypeError: This document requires 'TrustedHTML', often in lazy-loaded chunks, so test with the strictest CSP in e2e.

// main.ts bootstrap with trusted types awareness
if (window.trustedTypes && trustedTypes.createPolicy) {
  trustedTypes.createPolicy('angular#bundler', { createScriptURL: (u: string) => u });
}

1090. How does Angular's HttpClient XSRF protection work, and what backend contract and edge cases must you handle for cross-origin or cookie-less (Bearer token) auth?

HttpClient reads a cookie named XSRF-TOKEN and adds X-XSRF-TOKEN to mutating requests automatically. The backend must set that cookie with SameSite appropriate to the topology and validate the header. Edge cases: (1) cross-origin APIs where the cookie is third-party require withCredentials: true and CORS preflight; (2) Bearer-token APIs often disable XSRF entirely and rely on the token's non-extractability, but then you must guard against token leakage via XSS; (3) SSR/transfer state can desync the cookie; (4) custom header/cookie names need HttpClientXsrfModule.withOptions(). Never disable XSRF globally to "fix" a 403; fix the cookie contract instead.

HttpClientXsrfModule.withOptions({
  cookieName: 'XSRF-TOKEN',
  headerName: 'X-XSRF-TOKEN',
})

1091. Where should JWT access/refresh tokens live in an Angular SPA, and how do you design refresh-token rotation that minimizes XSS exfiltration and CSRF risk?

Access tokens in memory (a service-held variable) are immune to XSS theft but lost on reload; refresh tokens should be httpOnly, Secure, SameSite cookies scoped to the refresh endpoint, rotated on every use. Use short-lived access tokens, refresh-token rotation with reuse detection (invalidate the whole family on reuse), and a BFF if you need SSR. Avoid localStorage for refresh tokens; if you must persist access tokens, accept the XSS risk and harden with CSP/Trusted Types. Interceptors should attach the in-memory access token and, on 401, call refresh (serialized) then retry.

export const authInterceptor: HttpInterceptorFn = (req, next) => {
  const token = inject(TokenStore).accessToken(); // in-memory
  return next(req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }));
};

1092. How should a strict CSP be designed for an Angular application that uses inline styles, lazy-loaded chunks, and third-party analytics, without weakening security?

Use a nonce-based policy: script-src 'self' 'nonce-<random>' 'strict-dynamic' and style-src 'self' 'nonce-<random>', propagate the nonce to Angular via APP_INITIALIZER or bootstrap options so generated inline styles carry it. 'strict-dynamic' lets trusted scripts load lazy chunks without listing each hash. Avoid 'unsafe-inline'/'unsafe-eval'; use Trusted Types for DOM sinks. For third-party analytics, load via a trusted bootstrap script or hash allow-list, and isolate in a sandboxed iframe if possible. Set object-src 'none', base-uri 'self', and frame-ancestors appropriately.

Content-Security-Policy:
  default-src 'self';
  script-src 'self' 'nonce-RANDOM' 'strict-dynamic';
  style-src 'self' 'nonce-RANDOM';
  img-src 'self' data:;
  connect-src 'self' https://api.example.com;
  object-src 'none';
  base-uri 'self'

1093. How is Angular's DomSanitizer bypassSecurityTrustHtml dangerous on user input even after a custom regex, and what safe alternative should be used?

Calling bypassSecurityTrustHtml on user-controlled data disables sanitization for that value, so any missed payload (e.g., event handlers, nested tags) executes. Regex filtering is insufficient. Prefer binding textually or using Angular's sanitizer without bypass; reserve bypass for compile-time constants.

const html = this.sanitizer.bypassSecurityTrustHtml(this.comment.replace(/<script.*?>.*?<\\/script>/gis, ''));
// unsafe

1094. How does Angular integrate with Trusted Types under a strict CSP that disallows unsafe-eval, and what build/runtime settings are required?

Angular registers a Trusted Types policy; AOT builds avoid JIT eval. Configure CSP require-trusted-types-for 'script' with policy names Angular expects. Ensure Zone.js and lazy chunks comply; test in production mode.

Content-Security-Policy: default-src 'self'; script-src 'self'; require-trusted-types-for 'script'; trusted-types angular angular#bundler

1095. How does HttpClient XSRF protection work, and what server/client contract is needed for cross-origin deployments?

HttpClient reads XSRF-TOKEN cookie and sends X-XSRF-TOKEN header on mutating requests. Server must set cookie and validate header. Cross-origin requires withCredentials, CORS, and proper SameSite. Bearer-token APIs may disable XSRF but must handle XSS risk.

provideHttpClient(withXsrfConfiguration({
  cookieName: 'XSRF-TOKEN',
  headerName: 'X-XSRF-TOKEN'
}))

1096. Compare JWT storage strategies in an Angular SPA: localStorage, in-memory, and HttpOnly cookie. Which resists XSS best, and what trade-offs exist?

localStorage is XSS-exfiltratable; in-memory is safer but lost on refresh; HttpOnly cookies resist XSS but introduce CSRF and require SameSite/Secure flags plus refresh rotation. Interceptors attach in-memory access tokens.

export const authInterceptor: HttpInterceptorFn = (req, next) => {
  const token = inject(TokenStore).accessToken();
  return next(req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }));
};

1097. How do you design a strict CSP for Angular with inline styles, lazy chunks, and third-party analytics without weakening security?

Use nonce-based policy with strict-dynamic, propagate nonce to Angular, avoid unsafe-inline/unsafe-eval, use Trusted Types. Isolate third-party analytics. Set object-src none, base-uri self.

Content-Security-Policy:
  default-src 'self';
  script-src 'self' 'nonce-RANDOM' 'strict-dynamic';
  style-src 'self' 'nonce-RANDOM';
  img-src 'self' data:;
  connect-src 'self' https://api.example.com;
  object-src 'none';
  base-uri 'self'

1098. Standalone bootstrap and provider scoping

In an Angular 17+ standalone application, which configuration correctly bootstraps AppComponent while providing router and HTTP client at application level?

bootstrapApplication(AppComponent, {
  providers: [
    provideRouter(routes),
    provideHttpClient()
  ]
});

What subtle issue occurs if provideHttpClient() is instead added only inside a lazy-loaded route's providers array?

1099. Bundle budgets and tree-shaking

Given an angular.json budget:

"budgets": [
  { "type": "initial", "maximumWarning": "500kb", "maximumError": "1mb" }
]

Why can a component imported only through loadComponent still contribute to the initial bundle if it is referenced by a non-lazy barrel export?

1100. Module Federation shared dependencies

In a micro-frontend shell/remote setup, what happens when the shell and remote declare different required versions of @angular/core with singleton: true and strictVersion: true?

shared: {
  '@angular/core': { singleton: true, strictVersion: true, requiredVersion: '^17.0.0' }
}

1101. Monorepo boundary enforcement

In an Nx monorepo, how do project tags and depConstraints prevent a feature library from importing an application-specific utility, and what build error is produced when violated?

{
  "sourceTag": "scope:feature",
  "onlyDependOnLibsWithTags": ["scope:shared", "type:util"]
}

1102. Dynamic component creation lifecycle

When using ViewContainerRef.createComponent() with a standalone component, which cleanup step is required to avoid memory leaks, and how do signal inputs get updated on the created instance?

const ref = vcr.createComponent(DynamicCardComponent);
ref.setInput('title', 'New title');

1103. Multi-slot content projection

How does Angular resolve multiple <ng-content select=\"...\"> slots when projected content contains elements matching more than one selector, and what is the fallback behavior for unmatched content?

<ng-content select=\"[card-header]\"></ng-content>
<ng-content></ng-content>

1104. Signal inputs and change detection

Explain why a component using input.required<T>() and computed() can avoid manual ngOnChanges, and under what condition a parent update will not trigger child re-evaluation.

readonly id = input.required<string>();
readonly label = computed(() => this.id().toUpperCase());

1105. model() two-way binding

How does model() differ from input() plus output() for two-way binding, and what happens to parent state when this.value.set() is called inside the child?

readonly value = model<string>('');
this.value.set('updated');

1106. Resource API loading state

Using Angular's experimental resource API, how should a component handle status(), value(), and request cancellation when params changes rapidly?

const user = resource({
  params: () => ({ id: this.userId() }),
  loader: ({ params, abortSignal }) => fetchUser(params.id, { signal: abortSignal })
});

Reusable building blocks 14 questions

Components, modules, services, directives and pipes: how to design each one so it survives more than one screen — scope, public API, content projection, change detection cost and the point at which a shared piece stops paying for itself.

1107. What makes an Angular component genuinely reusable?

A component is reusable when it depends on its inputs and outputs, not on a route, a global store or a service it fetches data from. The rules I apply:

  • Data in through @Input (or the newer input() signal), events out through @Output.
  • No HttpClient inside a presentational component; a container component or the caller supplies the data.
  • No assumptions about the parent layout, the route or the CSS around it.
  • Styles that do not leak: default emulated encapsulation plus :host for the boundaries.
  • ChangeDetectionStrategy.OnPush, so the host decides when it renders and the component stays cheap.
  • Variable regions through <ng-content> instead of boolean inputs.

If a component ends up with five inputs and three outputs, it is usually two components or a service pretending to be one.

1108. Standalone components or NgModules for reusable building blocks?

Standalone is the modern default: a component, directive or pipe declares exactly what it imports, so the consumer adds only what it uses and tree-shaking works. NgModules still have a place in an existing codebase and in libraries that need to group providers or expose a secondary entry point.

The practical rule: one public API per folder, exported through an index.ts barrel. If the project keeps NgModules, the shared module contains declarations and exports only — never providers, because a provider imported twice by two lazy features silently creates two instances.

1109. How do you stop a shared module from becoming a dumping ground?

Three conditions before something enters the shared bucket: it is stateless, it is used by at least two features, and it depends on no feature. If it fails any of them, it stays in its feature folder.

  • No business vocabulary. A ShipmentStatusBadge is not shared; it is a cargo component. A StatusBadge with a colour input is shared.
  • No providers. Singletons belong to core or to providedIn: 'root'.
  • No data fetching. The moment it needs an API call it becomes a container, and containers are feature code.

A shared module that grows every sprint is usually a symptom of features importing each other's pieces instead of owning them.

1110. Component, directive or pipe: how do you choose?

Each exists to solve a different problem, and the choice is about what the output is:

  • Component — produces a template. Use it when there is markup to render.
  • Attribute directive — changes the behaviour or appearance of an element that already exists (focus, highlight, permission, tooltip). No template of its own.
  • Structural directive — decides whether a template is instantiated at all (*appIfLoaded, *appHasRole).
  • Pipe — transforms a value for display, with no side effects and no state.

Rule of thumb: if you need markup, a component; if you need existing markup to behave differently, a directive; if you need an existing value to display differently, a pipe.

1111. How do you write a reusable attribute directive?

A directive is reusable when it works on any element and takes its configuration as an input:

@Directive({ selector: '[appHighlightOnHover]', standalone: true })
export class HighlightOnHoverDirective {
  @Input('appHighlightOnHover') color = '#fff59d';

  constructor(private el: ElementRef<HTMLElement>, private r: Renderer2) {}

  @HostListener('mouseenter') onEnter() {
    this.r.setStyle(this.el.nativeElement, 'background', this.color);
  }
  @HostListener('mouseleave') onLeave() {
    this.r.removeStyle(this.el.nativeElement, 'background');
  }
}

Three details that matter: use Renderer2 instead of writing to nativeElement.style directly (it keeps the directive safe under server-side rendering and in web workers); alias the input with the selector name so [appHighlightOnHover]="'#ffe082'" works; and clean up anything you subscribe to in ngOnDestroy.

1112. How do you build a structural directive?

A structural directive receives a TemplateRef and decides whether to instantiate it inside a ViewContainerRef:

@Directive({ selector: '[appIfLoaded]', standalone: true })
export class IfLoadedDirective {
  constructor(private tpl: TemplateRef<unknown>, private vcr: ViewContainerRef) {}

  @Input() set appIfLoaded(loaded: boolean) {
    this.vcr.clear();
    if (loaded) { this.vcr.createEmbeddedView(this.tpl); }
  }
}

The microsyntax *appIfLoaded="flag" is sugar over an <ng-template> binding, which is why the input has to be named after the selector. Clearing before creating avoids duplicated views when the value flips, and the same pattern scales to permission checks or feature flags.

1113. What makes a service reusable, and root versus component scope?

A reusable service has one responsibility, no knowledge of the UI, and every dependency injected rather than imported directly. The scope is a lifecycle decision, not a style preference:

  • providedIn: 'root' — one instance for the application, tree-shaken away if nobody injects it. Correct for gateways, configuration and stateless helpers.
  • providers: [...] on a component — a fresh instance per component instance. Correct for wizard state, an editable form model, anything that must not leak between two open screens.
  • Providers declared in a lazy-loaded feature are scoped to that feature; loading it twice would create two copies.

A root service that holds per-screen data is the classic leak: the second screen reads the first screen's leftovers.

1114. How do you make a service substitutable in tests and across implementations?

Depend on an injection token typed to an interface instead of a concrete class:

export interface PricingGateway {
  quote(command: QuoteCommand): Observable<Quote>;
}

export const PRICING_GATEWAY =
  new InjectionToken<PricingGateway>('PRICING_GATEWAY');

The module decides whether the application receives the HTTP implementation, a mock or a caching decorator. The reusable library no longer imports HttpClient, consumers can swap REST for GraphQL without touching call sites, and tests provide a three-line fake instead of an HTTP harness.

1115. Pure versus impure pipes: what is the difference and when does it matter?

A pure pipe is called only when the input reference changes; Angular caches the result per input. An impure pipe (pure: false) runs on every change-detection cycle.

That difference is a performance decision: an impure sort or filter over a long list inside *ngFor re-runs dozens of times per second, and it also defeats memoisation, because every run produces a new array reference. Sorting, filtering and mapping belong in the component or a computed signal; pipes are for formatting — dates, currency, weights, translation — where the transformation is cheap and deterministic.

1116. How do you write a custom pipe, and how do you keep it reusable?

@Pipe({ name: 'weight', standalone: true })
export class WeightPipe implements PipeTransform {
  transform(value: number | null, unit: 'kg' | 'lb' = 'kg'): string {
    if (value === null || value === undefined) { return '—'; }
    return unit === 'kg'
      ? value.toFixed(1) + ' kg'
      : (value * 2.20462).toFixed(1) + ' lb';
  }
}

Keep it pure, keep it free of injected singletons (a pipe with a dependency is hard to test and hard to reuse), make it null-safe, and take configuration as arguments so one pipe covers several cases instead of five near-duplicates. Mark it standalone and export it from the folder barrel so consumers import it without a module.

1117. How does content projection make a component reusable?

<ng-content> moves the decision about the inner markup to the caller, which removes flags like [showFooter]:

<app-card>
  <h3 card-title>AWB 020-12345678</h3>
  <p>Booked, awaiting cut-off</p>
  <button card-actions>Rebook</button>
</app-card>

Inside the card: <ng-content select="[card-title]">, <ng-content select="[card-actions]"> and a plain <ng-content> as the fallback slot. When the parent has to supply a template that the child renders in its own context — a table cell, a list item — use <ng-template> plus ngTemplateOutlet with a context object instead of projecting markup.

1118. How do you keep the public API of a reusable component stable?

Treat inputs and outputs as a contract with consumers:

  • Required inputs stay required (input.required or a validation in ngOnInit), optional ones have a documented default.
  • Never mutate an object received through an input; emit a new one. Combined with OnPush, this is what makes the component predictable.
  • Do not rename or remove an input without a deprecation period, and do not leak internal types in the signature.
  • Expose behaviour through outputs and methods, never by letting the parent reach into internal state.
  • If other teams consume it, publish it as a library (ng-packagr, secondary entry points, semver) and keep a demo route or Storybook as living documentation.

1119. How do you test reusable components, directives and pipes?

  • Pipe — a pure function: instantiate it and assert input/output, including the null and edge cases.
  • Directive — a host component in TestBed that uses the directive on a real element; assert the DOM change and the cleanup.
  • Component — a host component that supplies inputs and records outputs, plus DOM assertions on what the user sees; one test per branch of the public API, not per internal method.
  • Contract — a compile-time test that imports only from the public barrel, so a refactor that breaks consumers fails the build instead of a screen.

If a reusable component needs HttpTestingController to be tested, it is not reusable yet: the data dependency belongs one level up.

1120. When is a component not worth making reusable?

When it has a single caller and no second use case in sight. Premature abstraction costs more than duplication: a component with a mode enum switching three templates, or five inputs where two are always passed together, is a sign that two screens were merged.

The rule I use is duplicate once, extract the third time — when the shape is proven by real callers. Code extracted after three real uses tends to survive; code extracted in advance usually gets a fourth boolean input and a comment explaining it.