Showing 50 question(s)

Answer:

Angular is a TypeScript-based open-source front-end framework developed by Google for building dynamic single-page applications (SPAs). It provides features like dependency injection, routing, forms, and component-based architecture.

Code Example:

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

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

Tags:

Answer:

Angular offers component-based architecture, TypeScript support, dependency injection, routing, two-way data binding, directives, pipes, reactive forms, RxJS, and lazy loading.

Code Example:

// Angular Features
✔ Components
✔ Services
✔ Routing
✔ Dependency Injection
✔ RxJS
✔ Reactive Forms

Tags:

Answer:

A component is the fundamental building block of an Angular application. It controls a portion of the UI using a TypeScript class, HTML template, and CSS styles.

Code Example:

@Component({
  selector: 'app-user',
  template: '<h2>{{name}}</h2>'
})

export class UserComponent {
  name = 'John';
}

Tags:

Answer:

An Angular module groups related components, directives, pipes, and services into a single unit. In standalone Angular applications, modules are optional.

Code Example:

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

export class AppModule { }

Tags:

Answer:

Data binding synchronizes data between the component and the template. Angular supports interpolation, property binding, event binding, and two-way binding.

Code Example:

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

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

<!-- Event Binding -->
<button (click)="save()">Save</button>

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

Tags:

Answer:

Directives are classes that add behavior to HTML elements. Angular provides component directives, structural directives, and attribute directives.

Code Example:

<p *ngIf="isLoggedIn">
  Welcome User
</p>

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

Tags:

Answer:

ngIf conditionally adds or removes elements from the DOM, whereas ngFor repeats an element for each item in a collection.

Code Example:

<div *ngIf="isAdmin">
  Admin Panel
</div>

<li *ngFor="let user of users">
  {{user.name}}
</li>

Tags:

Answer:

A service is used to share business logic, reusable functionality, or data across multiple components using dependency injection.

Code Example:

@Injectable({
  providedIn: 'root'
})

export class UserService {

  getUsers() {
    return ['John', 'Alice'];
  }

}

Tags:

Answer:

Dependency Injection (DI) is a design pattern where Angular automatically creates and injects required service instances into components or other services.

Code Example:

constructor(
  private userService: UserService
) {}

ngOnInit() {
  console.log(this.userService.getUsers());
}

Tags:

Answer:

Lifecycle hooks are methods that allow developers to respond to events during a component's lifecycle such as initialization, changes, rendering, and destruction.

Code Example:

export class AppComponent
implements OnInit, OnDestroy {

  ngOnInit() {
    console.log('Component Loaded');
  }

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

}

Tags:

Answer:

Angular Routing enables navigation between different views or components without reloading the page. It is configured using the Angular Router module.

Code Example:

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

bootstrapApplication(AppComponent, {
  providers: [provideRouter(routes)]
});

Tags:

Answer:

routerLink is a directive used to navigate between routes declaratively in Angular templates.

Code Example:

<nav>
  <a routerLink="/">Home</a>
  <a routerLink="/about">About</a>
  <a routerLink="/contact">Contact</a>
</nav>

Tags:

Answer:

Template-driven forms are simple and rely on directives in the template, while Reactive Forms are model-driven, more scalable, and suitable for complex validation.

Code Example:

// Reactive Form
profileForm = new FormGroup({
  name: new FormControl(''),
  email: new FormControl('')
});

Tags:

Answer:

ngModel is a directive that enables two-way data binding between form controls and component properties.

Code Example:

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

<p>{{ username }}</p>

Tags:

Answer:

Pipes transform data before displaying it in the template. Angular provides built-in pipes such as date, currency, uppercase, lowercase, and json.

Code Example:

<p>{{ today | date }}</p>

<p>{{ price | currency }}</p>

<p>{{ name | uppercase }}</p>

Tags:

Answer:

A custom pipe is created using the @Pipe decorator and implementing the PipeTransform interface.

Code Example:

@Pipe({
  name: 'capitalize'
})

export class CapitalizePipe
implements PipeTransform {

  transform(value: string): string {
    return value.toUpperCase();
  }

}

Tags:

Answer:

Structural directives change the DOM layout (such as *ngIf and *ngFor), while attribute directives modify the appearance or behavior of existing elements (such as ngClass and ngStyle).

Code Example:

<!-- Structural -->
<div *ngIf="show">
  Hello
</div>

<!-- Attribute -->
<div [ngClass]="'active'">
  Angular
</div>

Tags:

Answer:

Components communicate using @Input(), @Output(), shared services, ViewChild, or RxJS Subjects.

Code Example:

@Input()
title!: string;

@Output()
save = new EventEmitter<void>();

this.save.emit();

Tags:

Answer:

@Injectable() marks a class as available for dependency injection and allows Angular to create and inject its dependencies.

Code Example:

@Injectable({
  providedIn: 'root'
})

export class ProductService {

  getProducts() {
    return [];
  }

}

Tags:

Answer:

Angular uses HttpClient from @angular/common/http to perform GET, POST, PUT, DELETE, and other HTTP requests.

Code Example:

constructor(
  private http: HttpClient
) {}

this.http.get<User[]>(
  'https://api.example.com/users'
).subscribe(users => {
  console.log(users);
});

Tags:

Answer:

RxJS (Reactive Extensions for JavaScript) is a library for reactive programming using Observables. Angular uses RxJS extensively for asynchronous operations like HTTP requests and event handling.

Code Example:

import { of } from 'rxjs';

of(1, 2, 3).subscribe(value => {
  console.log(value);
});

Tags:

Answer:

An Observable is a stream of data that emits values over time. Components subscribe to Observables to receive asynchronous data.

Code Example:

this.http.get('/api/users')
  .subscribe(users => {
    console.log(users);
  });

Tags:

Answer:

A Promise emits a single value and cannot be cancelled, whereas an Observable can emit multiple values over time and supports cancellation through unsubscribe().

Code Example:

const promise = fetch('/api/users');

const observable = this.http.get('/api/users');

observable.subscribe(data => {
  console.log(data);
});

Tags:

Answer:

Unsubscribing prevents memory leaks by releasing resources when a component is destroyed.

Code Example:

subscription!: Subscription;

ngOnInit() {
  this.subscription =
    this.userService.getUsers()
      .subscribe();
}

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

Tags:

Answer:

Lazy Loading loads feature modules only when they are needed, reducing the initial bundle size and improving application performance.

Code Example:

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

Tags:

Answer:

Angular automatically sanitizes HTML, URLs, and styles to prevent Cross-Site Scripting (XSS) attacks.

Code Example:

<div [innerHTML]="content">
</div>

Tags:

Answer:

ViewChild is a decorator used to access child components, directives, or DOM elements from a parent component.

Code Example:

@ViewChild('inputBox')
input!: ElementRef;

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

Tags:

Answer:

ngOnChanges() is called whenever an @Input() property changes. It allows a component to react to input changes.

Code Example:

ngOnChanges(changes: SimpleChanges) {

  console.log(changes);

}

Tags:

Answer:

ngAfterViewInit() is called once after Angular initializes the component view and child views. It is commonly used with ViewChild.

Code Example:

ngAfterViewInit() {

  console.log('View Initialized');

}

Tags:

Answer:

Change Detection is the process Angular uses to update the DOM whenever application data changes. Angular supports Default and OnPush change detection strategies.

Code Example:

@Component({
  selector: 'app-user',
  templateUrl: './user.html',
  changeDetection: ChangeDetectionStrategy.OnPush
})

export class UserComponent { }

Tags:

Answer:

Standalone Components eliminate the need for NgModules. They can directly import other standalone components, directives, and pipes, simplifying Angular applications.

Code Example:

@Component({
  selector: 'app-home',
  standalone: true,
  imports: [CommonModule],
  template: '<h2>Home</h2>'
})

export class HomeComponent { }

Tags:

Answer:

Angular CLI is a command-line interface that helps developers create, build, test, serve, and deploy Angular applications efficiently.

Code Example:

ng new my-app

ng generate component home

ng serve

ng build

Tags:

Answer:

Common CLI commands include ng new, ng serve, ng build, ng generate, ng test, and ng lint.

Code Example:

ng generate component dashboard

ng generate service user

ng test

ng build --configuration production

Tags:

Answer:

Route Guards control navigation by determining whether a user can access or leave a route. Examples include CanActivate, CanDeactivate, CanLoad, and CanMatch.

Code Example:

export const authGuard: CanActivateFn =
(route, state) => {

  return true;

};

Tags:

Answer:

Validators ensure that user input meets specified rules. Angular provides built-in validators and also supports custom validators.

Code Example:

name = new FormControl('', [
  Validators.required,
  Validators.minLength(3),
  Validators.email
]);

Tags:

Answer:

Template reference variables allow direct access to DOM elements or Angular components inside templates using the # symbol.

Code Example:

<input #username>

<button
(click)="show(username.value)">
Show
</button>

Tags:

Answer:

ng-template defines a template that is not rendered immediately. It is commonly used with structural directives like ngIf and ngTemplateOutlet.

Code Example:

<ng-template #loading>

  <p>Loading...</p>

</ng-template>

<div *ngIf="loaded; else loading">
  Content Loaded
</div>

Tags:

Answer:

ng-container groups multiple elements without adding an extra element to the DOM.

Code Example:

<ng-container *ngIf="loggedIn">

  <h2>Welcome</h2>

  <p>User Dashboard</p>

</ng-container>

Tags:

Answer:

NgRx is a reactive state management library for Angular based on Redux principles. It uses Store, Actions, Reducers, Effects, and Selectors.

Code Example:

this.store.dispatch(
  loadUsers()
);

this.store.select(
  selectUsers
).subscribe(users => {

  console.log(users);

});

Tags:

Answer:

TrackBy improves ngFor performance by allowing Angular to identify list items using a unique key instead of recreating the entire DOM.

Code Example:

<li
*ngFor="let user of users;
trackBy: trackById">

{{ user.name }}

</li>

// Component
trackById(index: number, user: any) {
  return user.id;
}

Tags:

Answer:

Signals are a reactive state management feature introduced in Angular 16. They automatically notify Angular when their values change, reducing the need for manual change detection.

Code Example:

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

count = signal(0);

increment() {
  this.count.update(value => value + 1);
}

console.log(this.count());

Tags:

Answer:

Signals are synchronous, lightweight, and ideal for local component state, whereas Observables are asynchronous and better suited for streams of data such as HTTP requests and events.

Code Example:

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

const username = signal('John');

username.set('Alice');

console.log(username());

Tags:

Answer:

HTTP errors can be handled using the catchError operator from RxJS or by implementing an HTTP Interceptor for centralized error handling.

Code Example:

this.http.get('/api/users')
.pipe(
  catchError(error => {
    console.error(error);
    return of([]);
  })
)
.subscribe();

Tags:

Answer:

An HTTP Interceptor intercepts all HTTP requests and responses. It is commonly used for authentication tokens, logging, caching, and global error handling.

Code Example:

export const authInterceptor:
HttpInterceptorFn = (req, next) => {

  const request = req.clone({
    setHeaders: {
      Authorization: 'Bearer TOKEN'
    }
  });

  return next(request);

};

Tags:

Answer:

Providers tell Angular how to create or supply a dependency. They can be registered at the root, module, component, or route level.

Code Example:

@Component({
  selector: 'app-home',
  providers: [UserService]
})

export class HomeComponent { }

Tags:

Answer:

Angular uses Jasmine and Karma for unit testing. Components are tested using TestBed to create a testing module and component fixture.

Code Example:

describe('AppComponent', () => {

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [AppComponent]
    });
  });

  it('should create', () => {
    const fixture =
      TestBed.createComponent(AppComponent);

    expect(fixture.componentInstance)
      .toBeTruthy();
  });

});

Tags:

Answer:

Performance can be improved using lazy loading, standalone components, OnPush change detection, TrackBy, AOT compilation, tree shaking, Signals, and optimized bundle sizes.

Code Example:

@Component({
  selector: 'app-users',
  changeDetection:
    ChangeDetectionStrategy.OnPush
})

export class UsersComponent { }

Tags:

Answer:

Use the Angular CLI production build command. It enables Ahead-of-Time (AOT) compilation, optimization, tree shaking, and minification.

Code Example:

ng build --configuration production

Tags:

Answer:

AOT compilation converts Angular templates into JavaScript during the build process instead of at runtime, resulting in faster rendering, smaller bundles, and earlier error detection.

Code Example:

ng build --configuration production

// AOT compilation is enabled
// automatically for production builds.

Tags:

Answer:

Follow a component-based architecture, use standalone components, organize code into feature folders, avoid business logic in templates, unsubscribe from Observables, use lazy loading, implement OnPush change detection where appropriate, use strict typing, and write unit tests.

Code Example:

// Best Practices
✔ Use Standalone Components
✔ Lazy Load Routes
✔ Use OnPush Strategy
✔ Keep Components Small
✔ Reuse Services
✔ Follow Angular Style Guide
✔ Write Unit Tests

Tags: