Basic Angular Questions

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: '

Hello, Angular!

', 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.



Hello, {{ name }}!

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.



Welcome, {{ name }}!

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.


{{ birthday | date:'longDate' }}

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: `
    
` }) 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.


Content to show when isVisible is true

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: '

{{ data }}

' }) export class ChildComponent { @Input() data: string; } @Component({ selector: 'app-parent', template: '' }) 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.


  • {{ item }}

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: '

Example component

' }) 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.

Content

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.

Red
Blue
Default

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.

{{ item.name }}
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.

Content to show when isVisible is true
Content to show when isVisible is false

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: ''
})
export class ChildComponent {
    @Input() data: string;
    @Output() event = new EventEmitter();

    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: '

Welcome to Angular!

', 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: `
    
` }) 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: '

Example component

' }) 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: ''
})
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: '

Example component

', 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: ' 

Hello {{ name }}

' }) 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: ''
})
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: '

Example component

' }) 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.

This is visible

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.

  • {{ item }}

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: '

Example component

', 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: '

Example component

' }) 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: '

Example component

' }) 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.


Hello {{ name }}

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: `
    
` }) 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: '

{{ data }}

' }) 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: ''
})
export class ChildComponent {
    @Output() dataSent = new EventEmitter();

    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: '

HTTP request component

' }) 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: ''
})
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.

Case 1

Case 2

Default case

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.

Styled text

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.


    

Content is visible

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: `
    
Name is required
` }) 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.


Hello {{ name }}

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.

  • {{ item }}

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.

Content is visible

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: '

{{ data }}

' }) 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: '

Welcome to Angular!

' }) 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: '

Example component

' }) 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: `
    
` }) 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.


Hello {{ name }}

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.

  • {{ item }}

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.

Styled text

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: ``
})
export class ChildComponent {
    @Output() message = new EventEmitter();

    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.



            

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.

Content is visible

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: ``
})
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: `
    
` }) 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.



            

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.

Case 1

Case 2

Default case

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: '

{{ value }}

' }) 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.

Styled text

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: '

Check console for HTTP request result

' }) 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: '

Example component

' }) 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.


Hello {{ name }}

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.

  • {{ item }}

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.

Styled text

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: ``
})
export class ChildComponent {
    @Output() message = new EventEmitter();

    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.



            

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.

Content is visible

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: ``
})
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: `
    
` }) 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.



            

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.

Case 1

Case 2

Default case

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: '

{{ value }}

' }) 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.

Styled text

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: '

Check console for HTTP request result

' }) 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: '

Example component

' }) 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: '

{{ message }}

' }) 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.

Your username is: {{ username }}

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: `
    

Email is required and must be valid

` }) 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.

  • {{ item.key }}: {{ item.value }}

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: ``
})
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.

Dynamic style content

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.

Case 1
Case 2
Default case

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: '

Data: {{ data }}

' }) 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: '

{{ data }}

' }) 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.

Conditional classes

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: ''
})
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: ``
})
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: ''
})
export class ChildComponent {
    @Output() messageEvent = new EventEmitter();

    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: '

Data: {{ data }}

' }) 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: '

Component with cleanup

' }) export class ExampleComponent implements OnDestroy { ngOnDestroy() { console.log('Component destroyed'); } }

 

Basic Angular Questions - Part 15

1. 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: ''
})
export class CustomButtonComponent {
    @Output() clicked = new EventEmitter();

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

2. 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: ''
})
export class ExampleComponent {
    @ViewChild('inputElement') input!: ElementRef;

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

3. 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.

This content is visible

4. 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';
    }
}
            

5. 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.

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

6. 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;
}
            

7. 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));
    }
}
            

8. 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: ''
})
export class ParentComponent implements AfterContentInit {
    @ContentChild('content') content!: ElementRef;

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

9. 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: '

{{ data }}

' }) export class ChildComponent { @Input() data!: string; }

10. 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.

Content

11. 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) { }
}
            

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

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


Value: {{ value }}

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

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

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


    

This is a template

Content when condition is true

14. 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: '

{{ data }}

' }) export class ExampleComponent implements OnChanges { @Input() data!: string; ngOnChanges(changes: SimpleChanges) { console.log(changes); } }

15. 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: '

Component initialized

' }) export class ExampleComponent implements OnInit { ngOnInit() { console.log('Component initialized'); } }

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

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

Case 1

Case 2

Default case

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

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


    

Content is visible

18. 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.

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

19. 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 value: {{ inputValue }}

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

20. 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

1. 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.

This content is conditionally rendered

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

2. 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: '

Component Initialized

' }) export class ExampleComponent implements OnInit { ngOnInit() { console.log('Component Initialized'); } }

3. 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.

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

4. 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');
    }
}
            

5. 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.

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

6. 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: '

{{ data }}

' }) export class ChildComponent { @Input() data!: string; }

7. 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: ''
})
export class ButtonComponent {
    @Output() clicked = new EventEmitter();

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

8. 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 { }
            

9. How do you bind an event in Angular?

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




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

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

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


    

Content is visible

11. 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: '
...
' }) 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); } } }

12. 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);
    }
}
            

13. 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);
        });
    }
}
            

14. 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();
    }
}
            

15. 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 value: {{ inputValue }}

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

16. 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';
    }
}
            

17. 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 { }
            

18. 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());
    }
}
            

19. 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 { }
            

20. 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

1. 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
            

2. 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
}
            

3. 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.

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

4. How do you implement conditional rendering in Angular?

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

This content is conditionally rendered

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

5. 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 { }
            

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

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


{{ message }}

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

7. 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.

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

8. 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';
    }
}
            

9. 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 value: {{ inputValue }}

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

10. 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 { }
            

11. 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);
    }
}
            

12. 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('');
    }
}
            

13. 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());
    }
}
            

14. 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 { }
            

15. 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.

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

16. 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.


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); } }

17. 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();
    }
}
            

18. 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');
    }
}
            

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

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






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

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

20. 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: '',
})
export class ChildComponent {
    @Output() notifyEvent = new EventEmitter();

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

// Parent component template


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

Basic Angular Questions - Part 17

1. 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
            

2. 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
}
            

3. 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.

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

4. How do you implement conditional rendering in Angular?

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

This content is conditionally rendered

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

5. 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 { }
            

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

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


{{ message }}

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

7. 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.

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

8. 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';
    }
}
            

9. 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 value: {{ inputValue }}

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

10. 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 { }
            

11. 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);
    }
}
            

12. 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('');
    }
}
            

13. 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());
    }
}
            

14. 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 { }
            

15. 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.

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

16. 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.


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); } }

17. 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();
    }
}
            

18. 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');
    }
}
            

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

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






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

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

20. 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: '',
})
export class ChildComponent {
    @Output() notifyEvent = new EventEmitter();

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

// Parent component template


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

 

Basic Angular Questions - Part 18

1. 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 { }
            

2. 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

            

3. 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 }
];
            

4. 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());
    }
}
            

5. 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;
        });
    }
}
            

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

The `ngIf` directive conditionally includes or excludes elements in the DOM based on an expression.

This content is visible

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

7. 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.

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

8. 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: '',
})
export class ChildComponent {
    @Output() notifyEvent = new EventEmitter();

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

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

9. 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: '

{{ data }}

', }) export class ChildComponent { @Input() data: string; } // In the parent component @Component({ selector: 'app-parent', template: '', }) export class ParentComponent { parentData = 'Data from parent'; }

10. 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 { }
            

11. 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.


Name is required
// 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); } } }

12. 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

Hover over me!

13. 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 { }
            

14. 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());
    }
}
            

15. 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`.

{{ today | date:'shortDate' }}

{{ amount | currency:'USD' }}

{{ number | number:'1.2-2' }}

@Component({ selector: 'app-example', template: '...', }) export class ExampleComponent { today = new Date(); amount = 1234.56; number = 1234.5678; }

16. 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({});
    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' });
    }
}
            

17. 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);
            })
        );
    }
}
            

18. 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();
        }
    }
}
            

19. 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);
    }
}
            

20. 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.

Dynamic styling
@Component({ selector: 'app-example', template: '...', }) export class ExampleComponent { isRed = true; fontSize = 16; }

 

Basic Angular Questions - Part 19

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

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

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

2. 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] }
];
            

3. 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: '',
})
export class ParentComponent implements AfterContentInit {
    @ContentChild('header') header: ElementRef;
    @ContentChildren('item') items: QueryList;

    ngAfterContentInit() {
        console.log(this.header.nativeElement.textContent);
        this.items.forEach(item => console.log(item.nativeElement.textContent));
    }
}

// In the parent component template

    

Header

Item 1

Item 2

4. 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: '
', }) 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'); } }

5. 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);
    }
}
            

6. 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 { }
            

7. 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: `
        

Paragraph 1

Paragraph 2

`, }) export class ExampleComponent implements AfterViewInit { @ViewChild('paragraph') paragraph: ElementRef; @ViewChildren('paragraph') paragraphs: QueryList; ngAfterViewInit() { console.log(this.paragraph.nativeElement.textContent); this.paragraphs.forEach(p => console.log(p.nativeElement.textContent)); } }

8. 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

{{ 'Hello' | reverse }}

9. 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');
    }
}
            

10. 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();
    }
}
            

11. 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);
        }
    }
}
            

12. 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, next: HttpHandler): Observable> {
        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 }
]
            

13. 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: ``,
})
export class ChildComponent {
    @Input() message: string;
    @Output() notify: EventEmitter = new EventEmitter();

    notifyParent() {
        this.notify.emit('Hello from child');
    }
}

@Component({
    selector: 'app-parent',
    template: ``,
})
export class ParentComponent {
    parentMessage = 'Message from parent';

    onNotify(message: string) {
        console.log(message);
    }
}
            

14. 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)
    }
];
            

15. 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 { }
            

16. 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 { }
            

17. 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: `

{{ data$ | async }}

`, }) export class ExampleComponent { data$ = this.dataService.getData(); constructor(private dataService: DataService) { } }

18. 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.

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

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

The `ngIf` directive conditionally includes or excludes a block of HTML based on an expression.

Visible content

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

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

The `ngSwitch` directive allows you to conditionally include one of multiple elements based on a value.

Case A

Case B

Default case

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

 

Basic Angular Questions - Part 20

1. 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() { }
}
            

2. 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
        });
    }
}
            

3. 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');
    }
}
            

4. 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: `

Styled text

`, styles: [`p { color: green; }`], encapsulation: ViewEncapsulation.Emulated }) export class ExampleComponent { }

5. 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: `
`, }) 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'); } }

6. 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);
        });
    }
}
            

7. 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 { }
            

8. 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');
    }
}
            

9. 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);
    }
}
            

10. 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);
    }
}
            

11. 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: ``,
})
export class ChildComponent {
    @Input() childData: string;
    @Output() notify: EventEmitter = new EventEmitter();

    notifyParent() {
        this.notify.emit('Data from child');
    }
}

@Component({
    selector: 'app-parent',
    template: ``,
})
export class ParentComponent {
    parentData = 'Data from parent';

    handleNotify(data: string) {
        console.log(data);
    }
}
            

12. 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 { }
            

13. 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 { }
            

14. 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: `

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); } }

15. 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: `
Styled text
`, }) export class ExampleComponent { color = 'blue'; fontSize = '20px'; }

16. 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: `
Classy div
`, }) export class ExampleComponent { isActive = true; }

17. 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.

  • {{ entry.key }}: {{ entry.value }}
@Component({ selector: 'app-example', template: '...', }) export class ExampleComponent { object = { name: 'John', age: 30 }; }

18. How do you use Angular's `ngTemplateOutlet` directive?

`ngTemplateOutlet` is used to dynamically insert an ` ` into the DOM.


    

Template content

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

19. How do you use Angular's `ngContent` directive?

`ngContent` is used to project content into a component's template.


@Component({
    selector: 'app-example',
    template: ``,
})
export class ExampleComponent { }

@Component({
    selector: 'app-parent',
    template: `

Projected content

`, }) export class ParentComponent { }

20. 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;
}