Posted on: January 19, 2025 Posted by: rahulgite Comments: 0

This section provides detailed answers, examples, and implementation steps for fundamental Angular concepts.


1. What is Angular, and how is it different from AngularJS?

Answer:

Angular is a modern, open-source web application framework developed by Google. It uses TypeScript, a superset of JavaScript, and provides features like components, dependency injection, and reactive programming. AngularJS, on the other hand, is the first version of Angular based on JavaScript and follows an MVC (Model-View-Controller) architecture.

Key Differences:

  • Language: Angular uses TypeScript, whereas AngularJS uses JavaScript.
  • Architecture: Angular follows a component-based architecture, while AngularJS is MVC-based.
  • Performance: Angular offers better performance with Ahead-of-Time (AOT) compilation and optimized change detection.

2. Explain the architecture of Angular.

Answer:

Angular’s architecture is component-based and follows the following core building blocks:

  1. Modules: Organize an application into cohesive blocks.
  2. Components: Define the view and logic for a UI element.
  3. Templates: Describe the structure of the component’s view.
  4. Services: Provide reusable business logic or data access.
  5. Dependency Injection: Manage the lifecycle and provision of dependencies.
  6. Directives: Extend HTML functionality.
  7. Routing: Manage navigation between views.

3. What are lifecycle hooks in Angular?

Answer:

Lifecycle hooks are methods that Angular calls at different stages of a component’s lifecycle.

Key Hooks:

  1. ngOnInit: Invoked after component initialization.
  2. ngOnChanges: Responds to input property changes.
  3. ngDoCheck: Detects changes that Angular doesn’t catch.
  4. ngAfterContentInit: Runs after content projection.
  5. ngAfterContentChecked: Runs after every content check.
  6. ngAfterViewInit: Invoked after the component’s view is initialized.
  7. ngAfterViewChecked: Runs after every view check.
  8. ngOnDestroy: Cleans up before the component is destroyed.

Angular Lifecycle Hooks (with Examples)

✅ 1. ngOnInit()

Called once, after the component is initialized and its input properties are set.

📦 Use it for: Initializing data, calling services.

EditngOnInit() {
console.log('Component initialized');
this.loadUsers();
}

🔁 2. ngOnChanges(changes: SimpleChanges)

Called whenever an @Input() property changes.

📦 Use it for: Reacting to parent component changes.

@Input() userId: number;

ngOnChanges(changes: SimpleChanges) {
if (changes['userId']) {
this.fetchUserDetails(changes['userId'].currentValue);
}
}

🔍 3. ngDoCheck()

Called on every change detection run, even if no inputs changed.

📦 Use it for: Custom change detection logic.

ngDoCheck() {
console.log('Change detection running...');
}

📥 4. ngAfterContentInit()

Called once after content is projected into the component via <ng-content>.

📦 Use it for: Interacting with projected content.

ngAfterContentInit() {
console.log('Content projected into the component');
}

🔁 5. ngAfterContentChecked()

Called after every check of the projected content.

📦 Use it for: Validation or reacting to content changes.

ngAfterContentChecked() {
console.log('Projected content checked');
}

🖼️ 6. ngAfterViewInit()

Called once after the component’s view (and child views) are initialized.

📦 Use it for: Accessing @ViewChild or DOM.

@ViewChild('inputRef') input: ElementRef;

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

🔁 7. ngAfterViewChecked()

Called after every check of the component’s view and its children.

📦 Use it for: Updating something after view changes.

ngAfterViewChecked() {
console.log('View checked');
}

❌ 8. ngOnDestroy()

Called just before the component is destroyed.

📦 Use it for: Cleanup (unsubscribe, clear intervals, etc.)

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

📊 Summary Table

Hook NameWhen It RunsCommon Use
ngOnInit()After component setupInit logic, API calls
ngOnChanges()On @Input() changeSync input
ngDoCheck()Custom change detectionDeep object changes
ngAfterContentInit()After <ng-content> insertionAccess projected content
ngAfterContentChecked()After content checkValidation
ngAfterViewInit()After component view initAccess ViewChild
ngAfterViewChecked()After view checkDOM updates
ngOnDestroy()Before component is destroyedCleanup

Example:

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

4. What is data binding in Angular?

Answer:

Data binding in Angular synchronizes the data between the component and the view. It ensures the model and view are updated automatically.

Types of Data Binding:

  1. Interpolation: One-way binding from the component to the template. <p>{{ message }}</p>
  2. Property Binding: Binds an element property to a component property. <img [src]="imageUrl" />
  3. Event Binding: Binds a component event to a method. <button (click)="onClick()">Click Me</button>
  4. Two-Way Binding: Synchronizes data between the component and the template. <input [(ngModel)]="name" />

5. Explain the difference between ngIf and ngSwitch.

Answer:

  • ngIf: Conditionally includes or excludes an element based on a boolean expression. <p *ngIf="isVisible">Visible</p>
  • ngSwitch: Switches between multiple templates based on a matching expression. <div [ngSwitch]="value"> <p *ngSwitchCase="'A'">Case A</p> <p *ngSwitchCase="'B'">Case B</p> <p *ngSwitchDefault>Default</p> </div>

6. What is the difference between reactive and template-driven forms?

Answer:

  • Template-Driven Forms: Define form logic in the template using directives like ngModel.
  • Reactive Forms: Define form logic in the component using FormControl and FormGroup.

Example:

  • Template-Driven: <form> <input [(ngModel)]="name" name="name" /> </form>
  • Reactive: this.form = new FormGroup({ name: new FormControl('') });

7. How does Angular’s dependency injection system work?

Answer:

Angular’s DI system manages the creation and sharing of dependencies across components and services.

Steps:

  1. Define a service. @Injectable({ providedIn: 'root' }) export class DataService {}
  2. Inject it into a component. constructor(private dataService: DataService) {}

8. What is lazy loading, and how is it implemented in Angular?

Answer:

Lazy loading loads feature modules only when needed, improving performance.

Steps to Implement:

  1. Create a module and its routes.
  2. Configure loadChildren in the parent route. const routes: Routes = [ { path: 'feature', loadChildren: () => import('./feature/feature.module').then(m => m.FeatureModule) } ];

9. What is a pipe in Angular, and how is it used?

Answer:

Pipes transform data in templates. For example, formatting dates or currencies.

Example:

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

Custom Pipe:

@Pipe({ name: 'capitalize' })
export class CapitalizePipe implements PipeTransform {
  transform(value: string): string {
    return value.charAt(0).toUpperCase() + value.slice(1);
  }
}

10. What are Angular zones?

Answer:

Zones in Angular intercept and keep track of asynchronous operations, ensuring the application automatically updates the view when the model changes.

Example:

Using NgZone to trigger manual change detection:

constructor(private zone: NgZone) {}
this.zone.run(() => {
  this.data = updatedData;
});

11. What is Angular’s Change Detection Mechanism?

Answer:

Angular’s change detection checks for changes in the application state and updates the DOM accordingly. It uses a mechanism based on zones to track asynchronous operations and update views.


12. What is the purpose of the @Input and @Output decorators?

Answer:

  • @Input: Passes data from a parent component to a child component.
  • @Output: Sends events from a child component to a parent component.

Example:

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

  sendData() {
    this.messageEvent.emit('Hello Parent');
  }
}

Leave a Comment