Angular is a powerful and versatile framework for building web applications. Whether you're preparing for an interview or looking to deepen your understanding of Angular, this blog will cover advanced Angular concepts and provide detailed answers to common interview questions. Let's dive in!


Table of Contents

  1. What is Angular?
  2. What is the difference between AngularJS and Angular?
  3. What is TypeScript?
  4. Angular Architecture Diagram
  5. Key Components of Angular
  6. Directives in Angular
  7. Components in Angular
  8. Difference Between Component and Directive
  9. Templates in Angular
  10. Modules in Angular
  11. Lifecycle Hooks in Angular
  12. Data Binding in Angular
  13. Metadata in Angular
  14. Angular CLI
  15. Constructor vs ngOnInit
  16. Services in Angular
  17. Dependency Injection in Angular
  18. Dependency Hierarchy
  19. Async Pipe
  20. Inline vs External Templates
  21. ngFor Directive
  22. ngIf Directive
  23. Script Tag in Templates
  24. Interpolation in Angular
  25. Template Expressions
  26. Template Statements
  27. Data Binding Types
  28. Pipes in Angular
  29. Parameterized Pipes
  30. Chaining Pipes
  31. Custom Pipes
  32. Example of Custom Pipe
  33. Pure vs Impure Pipes
  34. Bootstrapping Module
  35. Observables in Angular
  36. HttpClient in Angular
  37. Using HttpClient
  38. Reading Full Response
  39. Error Handling in Angular
  40. RxJS in Angular
  41. Subscribing to Observables
  42. Observables vs Promises
  43. Multicasting in RxJS
  44. Error Handling in Observables
  45. Short Hand Notation for Subscribe
  46. Utility Functions in RxJS
  47. Observable Creation Functions
  48. Handling Observables Without Handlers
  49. Angular Elements
  50. Browser Support for Angular Elements
  51. Custom Elements
  52. Bootstrapping Custom Elements
  53. How Custom Elements Work
  54. Transferring Components to Custom Elements
  55. Mapping Rules Between Angular Components and Custom Elements
  56. Typings for Custom Elements
  57. Dynamic Components
  58. Types of Directives
  59. Creating Directives Using CLI
  60. Example of Attribute Directive

1. What is Angular?

Angular is a TypeScript-based open-source front-end framework developed by Google. It is used to build dynamic, single-page applications (SPAs) and progressive web apps (PWAs). Angular provides a robust set of tools and features, including declarative templates, dependency injection, and end-to-end tooling, to simplify the development process.


2. What is the difference between AngularJS and Angular?

AngularJS Angular
Based on MVC architecture Based on component-based architecture
Uses JavaScript Uses TypeScript
No mobile support Mobile-friendly
Difficult to create SEO-friendly apps Easier to create SEO-friendly apps

3. What is TypeScript?

TypeScript is a typed superset of JavaScript developed by Microsoft. It adds optional static typing, classes, and interfaces to JavaScript, making it more suitable for large-scale applications. Angular is built entirely using TypeScript.

Example:

function greet(name: string): string {
    return `Hello, ${name}`;
}

4. Angular Architecture Diagram

Angular applications are built using a modular architecture. The main building blocks include:

  • Components: Control the UI.
  • Modules: Organize the application into cohesive blocks of functionality.
  • Services: Provide shared functionality across components.
  • Templates: Define the views.
  • Metadata: Adds additional information to Angular classes.

Angular Architecture


5. Key Components of Angular

  • Components: Basic UI building blocks.
  • Modules: Logical boundaries for organizing code.
  • Templates: Define the views.
  • Services: Provide shared functionality.
  • Metadata: Adds additional information to Angular classes.

6. Directives in Angular

Directives are used to add behavior to DOM elements. There are three types of directives:

  1. Component Directives: Directives with a template.
  2. Structural Directives: Change the DOM layout (e.g., *ngIf, *ngFor).
  3. Attribute Directives: Change the appearance or behavior of an element (e.g., ngStyle, ngClass).

Example:

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

7. Components in Angular

Components are the most basic UI building blocks in Angular. They consist of:

  • A template: Defines the view.
  • A class: Contains the logic.
  • Metadata: Defined using the @Component decorator.

Example:

@Component({
    selector: 'app-root',
    template: `{{title}}`
})
export class AppComponent {
    title = 'Hello, Angular!';
}

8. Difference Between Component and Directive

Component Directive
Always has a template Does not have a template
Only one component per element Multiple directives per element
Used to create UI widgets Used to add behavior to existing elements

9. Templates in Angular

Templates define the view of an Angular component. They can be inline or external.

Inline Template:

@Component({
    selector: 'app-root',
    template: `{{title}}`
})

External Template:

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html'
})

10. Modules in Angular

Modules are used to organize an application into cohesive blocks of functionality. The root module is called AppModule.

Example:

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

11. Lifecycle Hooks in Angular

Angular components go through a lifecycle, and Angular provides hooks to tap into key moments:

  1. ngOnChanges: Called when input properties change.
  2. ngOnInit: Called after the component is initialized.
  3. ngDoCheck: Called during change detection.
  4. ngAfterContentInit: Called after content is projected.
  5. ngAfterViewInit: Called after the view is initialized.
  6. ngOnDestroy: Called before the component is destroyed.

12. Data Binding in Angular

Data binding is a mechanism to synchronize data between the component and the view. There are four types of data binding:

  1. Interpolation: {{value}}
  2. Property Binding: [property]="value"
  3. Event Binding: (event)="handler"
  4. Two-Way Binding: [(ngModel)]="value"

13. Metadata in Angular

Metadata is used to decorate Angular classes with additional information. It is defined using decorators like @Component, @Directive, and @NgModule.

Example:

@Component({
    selector: 'app-root',
    template: `{{title}}`
})

14. Angular CLI

Angular CLI is a command-line interface for scaffolding and building Angular applications. It provides commands like:

  • ng new: Create a new project.
  • ng generate: Generate components, services, etc.
  • ng serve: Run the application.

15. Constructor vs ngOnInit

  • Constructor: Used for dependency injection and initializing class members.
  • ngOnInit: Used for Angular-specific initialization logic.

Example:

export class AppComponent implements OnInit {
    constructor() { }
    ngOnInit() { }
}

16. Services in Angular

Services are used to share data and functionality across components. They are typically injected into components using dependency injection.

Example:

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

17. Dependency Injection in Angular

Dependency Injection (DI) is a design pattern in which a class requests dependencies from external sources rather than creating them itself. Angular's DI framework provides dependencies to classes.

Example:

constructor(private dataService: DataService) { }

18. Dependency Hierarchy

Angular's DI system forms a hierarchy of injectors. When a dependency is requested, Angular looks for it in the current injector. If not found, it looks up the hierarchy.


19. Async Pipe

The async pipe subscribes to an observable or promise and returns the latest value. It automatically handles subscription and unsubscription.

Example:

{{ data$ | async }}

20. Inline vs External Templates

  • Inline Templates: Defined directly in the component using the template property.
  • External Templates: Defined in a separate HTML file and linked using the templateUrl property.

21. ngFor Directive

The *ngFor directive is used to iterate over a list and display each item.

Example:

*ngFor="let item of items">{{ item }}

22. ngIf Directive

The *ngIf directive conditionally includes or excludes an element based on a boolean expression.

Example:

*ngIf="isVisible">Content

23. Script Tag in Templates

Angular automatically sanitizes content to prevent XSS attacks. If you use a tag inside a template, it will be ignored, and a warning will be logged.


24. Interpolation in Angular

Interpolation is used to bind data to the view using double curly braces {{ }}.

Example:

{{ title }}

25. Template Expressions

Template expressions are JavaScript-like expressions used within templates to produce a value.

Example:

{{ 1 + 1 }}

26. Template Statements

Template statements are used to respond to events in the template.

Example:

(click)="onClick()">Click Me

27. Data Binding Types

Data binding can be categorized into:

  1. One-Way Binding: From component to view ({{value}}, [property]="value").
  2. Event Binding: From view to component ((event)="handler").
  3. Two-Way Binding: Combines property and event binding ([(ngModel)]="value").

28. Pipes in Angular

Pipes are used to transform data in templates. Angular provides built-in pipes like date, uppercase, and currency.

Example:

{{ date | date:'fullDate' }}

29. Parameterized Pipes

Pipes can accept parameters to customize their behavior.

Example:

{{ date | date:'shortDate' }}

30. Chaining Pipes

Pipes can be chained to apply multiple transformations.

Example:

{{ date | date:'fullDate' | uppercase }}

31. Custom Pipes

Custom pipes can be created to implement custom transformation logic.

Example:

@Pipe({ name: 'customPipe' })
export class CustomPipe implements PipeTransform {
    transform(value: any, ...args: any[]): any {
        return value.toUpperCase();
    }
}

32. Example of Custom Pipe

A custom pipe to transform file sizes:

@Pipe({ name: 'fileSize' })
export class FileSizePipe implements PipeTransform {
    transform(size: number, extension: string = 'MB'): string {
        return (size / (1024 * 1024)).toFixed(2) + extension;
    }
}

Usage:

{{ fileSize | fileSize:'GB' }}

33. Pure vs Impure Pipes

  • Pure Pipes: Only executed when the input value changes.
  • Impure Pipes: Executed on every change detection cycle.

34. Bootstrapping Module

The bootstrapping module is the root module that Angular uses to start the application. It is typically named AppModule.


35. Observables in Angular

Observables are used to handle asynchronous data streams. They are part of the RxJS library and are used extensively in Angular for HTTP requests, event handling, and more.


36. HttpClient in Angular

HttpClient is a service provided by Angular to make HTTP requests. It simplifies the process of sending and receiving data from a server.

Example:

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

37. Using HttpClient

To use HttpClient, you need to:

  1. Import HttpClientModule in your module.
  2. Inject HttpClient in your service.

Example:

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

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

38. Reading Full Response

To read the full HTTP response, use the observe option:

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

39. Error Handling in Angular

Error handling in Angular can be done using the catchError operator from RxJS.

Example:

this.http.get('https://api.example.com/data').pipe(
    catchError(error => {
        console.error('An error occurred:', error);
        return throwError('Something went wrong');
    })
).subscribe();

40. RxJS in Angular

RxJS (Reactive Extensions for JavaScript) is a library for reactive programming using observables. It is used in Angular for handling asynchronous operations.


41. Subscribing to Observables

To receive data from an observable, you need to subscribe to it.

Example:

observable.subscribe(
    data => console.log(data),
    error => console.error(error),
    () => console.log('Complete')
);

42. Observables vs Promises

Observables Promises
Can emit multiple values Emit a single value
Lazy execution Eager execution
Can be canceled Cannot be canceled

43. Multicasting in RxJS

Multicasting is the process of broadcasting data to multiple subscribers using a single execution.

Example:

const source = Rx.Observable.from([1, 2, 3]);
const subject = new Rx.Subject();
const multicasted = source.multicast(subject);

multicasted.subscribe(observerA);
multicasted.subscribe(observerB);

44. Error Handling in Observables

Error handling in observables is done using the error callback in the subscribe method.

Example:

observable.subscribe(
    data => console.log(data),
    error => console.error(error)
);

45. Short Hand Notation for Subscribe

The subscribe method can be written in shorthand notation:

observable.subscribe(
    data => console.log(data),
    error => console.error(error),
    () => console.log('Complete')
);

46. Utility Functions in RxJS

RxJS provides utility functions like map, filter, and merge to manipulate observables.

Example:

observable.pipe(
    map(data => data * 2),
    filter(data => data > 10)
).subscribe();

47. Observable Creation Functions

RxJS provides functions like from, of, and interval to create observables.

Example:

const observable = Rx.Observable.from([1, 2, 3]);

48. Handling Observables Without Handlers

If you don't provide handlers for next, error, or complete, the observable will ignore those notifications.


49. Angular Elements

Angular Elements allow you to package Angular components as custom elements, which can be used in non-Angular environments.


50. Browser Support for Angular Elements

Angular Elements are supported in modern browsers like Chrome, Firefox, Safari, and Edge.


51. Custom Elements

Custom elements are a web standard for defining new HTML elements. Angular Elements uses this standard to create reusable components.


52. Bootstrapping Custom Elements

Custom elements do not require bootstrapping. They are automatically initialized when added to the DOM.


53. How Custom Elements Work

Custom elements work by registering a class with the browser's CustomElementRegistry. When the element is added to the DOM, the browser creates an instance of the class.


54. Transferring Components to Custom Elements

To transfer an Angular component to a custom element, use the createCustomElement function.

Example:

const customElement = createCustomElement(AppComponent, { injector });
customElements.define('app-element', customElement);

55. Mapping Rules Between Angular Components and Custom Elements

  • Inputs: Map to attributes.
  • Outputs: Map to custom events.

56. Typings for Custom Elements

You can define typings for custom elements using NgElement and WithProperties.

Example:

const element = document.createElement('app-element') as NgElement & WithProperties<{ input: string }>;
element.input = 'value';

57. Dynamic Components

Dynamic components are components that are created at runtime. They are not defined in the template but are instantiated programmatically.


58. Types of Directives

There are three types of directives:

  1. Component Directives: Directives with a template.
  2. Structural Directives: Change the DOM layout.
  3. Attribute Directives: Change the appearance or behavior of an element.

59. Creating Directives Using CLI

You can create a directive using the Angular CLI:

ng generate directive highlight

60. Example of Attribute Directive

An attribute directive to change the background color:

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

Usage:

appHighlight>Highlight me!

Conclusion

Angular is a powerful framework with a rich set of features for building modern web applications. By understanding these advanced concepts, you'll be well-prepared for Angular interviews and capable of building robust, scalable applications. Happy coding! 🚀