Explain encapsulation in Angular

Encapsulation in Angular refers to the technique of creating a boundary or shield around a component or class, such that its properties and methods are protected and can only be accessed by other members of the same component or class. This helps in enforcing a consistent and reliable interface, as well as providing a layer of abstraction that can be used to hide the internal workings of the component or class from the rest of the application.

For example, consider the following component in Angular:

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

@Component({
  selector: 'app-example',
  template: `
    <h1>{{ title }}</h1>
    <button (click)="changeTitle()">Change Title</button>
  `
})
export class ExampleComponent {
  title = 'Hello, World!';

  changeTitle() {
    this.title = 'The title has changed!';
  }
}

In this example, the ExampleComponent class encapsulates the properties and methods related to the component. The title property represents the text that is displayed in the component, while the changeTitle() method is used to change the value of the title property when the button is clicked.

These properties and methods are only accessible within the ExampleComponent class and cannot be accessed or modified directly from outside the component. This helps ensure that the component behaves consistently and reliably, even if changes are made to the underlying implementation.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *