Access modifiers control who can use or change parts of a component. They help keep your code safe and organized.
Access modifiers in components in 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.
export class UserComponent { public username = 'Alice'; private password = '1234'; protected role = 'admin'; }
export class ProductComponent { private price = 100; public getPrice() { return this.price; } }
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.
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; } }
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.
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.