0
0
Angularframework~5 mins

Access modifiers in components in Angular

Choose your learning style9 modes available
Introduction

Access modifiers control who can use or change parts of a component. They help keep your code safe and organized.

When you want to hide some details inside a component so others can't change them by mistake.
When you want to allow only certain parts of your app to use or change a value or function.
When you want to make your component easier to understand by showing only important parts.
When you want to protect data inside a component from being changed directly.
When you want to share some data or functions with templates but keep others private.
Syntax
Angular
class MyComponent {
  public name: string;    // accessible everywhere
  private secret: string; // accessible only inside this class
  protected age: number;  // accessible inside this class and subclasses
}

public means anyone can access it.

private means only the component itself can access it.

protected means the component and its child classes can access it.

Examples
This component has a public username anyone can see, a private password only inside the component, and a protected role for child classes.
Angular
export class UserComponent {
  public username = 'Alice';
  private password = '1234';
  protected role = 'admin';
}
The price is private but can be read using the public getPrice() method.
Angular
export class ProductComponent {
  private price = 100;
  public getPrice() {
    return this.price;
  }
}
Sample Program

This Angular component shows how public and private access modifiers work. The template can show publicInfo directly but cannot access secretInfo directly. Instead, it uses a public method getSecret() to get the private data.

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

@Component({
  selector: 'app-sample',
  template: `<p>{{ publicInfo }}</p><p>{{ getSecret() }}</p>`
})
export class SampleComponent {
  public publicInfo = 'Visible to everyone';
  private secretInfo = 'Hidden from template';

  public getSecret() {
    return this.secretInfo;
  }
}
OutputSuccess
Important Notes

Templates can only access public members of the component.

Use private to hide details that should not be changed outside the component.

protected is useful when you extend components and want child classes to access some members.

Summary

Access modifiers control visibility and safety of component parts.

public is open to all, private is hidden inside the component, and protected is for the component and its children.

Templates can only use public members directly.