0
0
Angularframework~5 mins

Component selector usage in Angular

Choose your learning style9 modes available
Introduction

Component selectors let you place Angular components inside HTML. They tell Angular where to show your component's content.

You want to reuse a piece of UI in different parts of your app.
You need to organize your app into small, manageable parts.
You want to add a custom button or widget inside a page.
You want to build a navigation menu that appears on many pages.
Syntax
Angular
@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.css']
})
export class ExampleComponent {}

The selector is a string that looks like an HTML tag or attribute.

You use the selector as a tag in your HTML to show the component.

Examples
This component uses a simple tag selector app-hello. Use it as <app-hello></app-hello> in HTML.
Angular
@Component({ selector: 'app-hello', template: '<p>Hello!</p>' })
export class HelloComponent {}
This uses an attribute selector [appHighlight]. Add it as an attribute like <div appHighlight></div>.
Angular
@Component({ selector: '[appHighlight]', template: '<p>Highlighted text</p>' })
export class HighlightComponent {}
This uses a class selector .app-card. Use it as <div class="app-card"></div>.
Angular
@Component({ selector: '.app-card', template: '<p>Card content</p>' })
export class CardComponent {}
Sample Program

This example shows two components. GreetingComponent uses the selector app-greeting. The AppComponent includes it in its template using the tag <app-greeting></app-greeting>. When the app runs, it shows the greeting message inside the main area.

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

@Component({
  selector: 'app-greeting',
  template: `<h2>Hello, Angular!</h2>`
})
export class GreetingComponent {}

@Component({
  selector: 'app-root',
  template: `<main>
    <app-greeting></app-greeting>
  </main>`
})
export class AppComponent {}
OutputSuccess
Important Notes

Selectors must be unique in your app to avoid conflicts.

Use kebab-case (lowercase with dashes) for selectors to follow Angular style.

Attribute and class selectors are less common but useful for special cases.

Summary

Component selectors tell Angular where to place components in HTML.

You can use tag, attribute, or class selectors.

Use selectors as HTML tags or attributes to show your components.