Selectors

Understand how Angular selectors identify components and directives and determine where they can be used inside templates.

Lesson content

What is an Angular Selector? A selector tells Angular which HTML element or attribute should create a component or apply a directive. Selectors are defined inside component or directive metadata. Simple Definition Selector = The template pattern Angular uses to find and apply a component or directive. Component Selector Example import { Component } from '@angular/core'; @Component({ selector: 'app-user-card', standalone: true, template: ` <h2>User Card</h2> ` }) export class UserCardComponent {} Using the Component <app-user-card></app-user-card> Selector Flow Angular reads the template ↓ Finds <app-user-card> ↓ Matches selector: app-user-card ↓ Creates UserCardComponent ↓ Renders component template Why Use the app Prefix? Angular applications commonly prefix component selectors with app- . app-header app-footer app-product-card app-user-profile A prefix helps distinguish application components from standard HTML elements and third-party components. Types of Angular Selectors Selector Type Syntax Common Use Element selector app-user Components Attribute selector [appHighlight] Directives Class selector .app-card Directives in limited cases Attribute-value selector [type="email"] Match specific attributes Combined selector button[appSave] Restrict directive usage 1. Element Selector An element selector matches a custom HTML element. It is the recommended selector style for Angular components. @Component({ selector: 'app-product-card', standalone: true, template: ` <p>Product Card</p> ` }) export class ProductCardComponent {} Usage <app-product-card></app-product-card> 2. Attribute Selector An attribute selector applies behaviour to an existing HTML element or component. It is commonly used for directives. import { Directive } from '@angular/core'; @Directive({ selector: '[appHighlight]', standalone: true, host: { style: 'background-color: yellow' } }) export class HighlightDirective {} Usage <p appHighlight> Highlighted text </p> Rendered Behaviour Existing <p> element + appHighlight directive ↓ Highlighted paragraph 3. Class Selector A class selector matches an element containing a particular CSS class. @Directive({ selector: '.app-special', standalone: true }) export class SpecialDirective {} Usage <div class="app-special"> Special content </div> Attribute selectors are generally clearer and more commonly used for Angular directives. 4. Attribute-Value Selector An attribute-value selector matches an element only when the attribute contains a specific static value. @Directive({ selector: 'input[type="email"]', standalone: true }) export class EmailInputDirective {} Matches <input type="email" /> Does Not Match <input type="text" /> 5. Combined Selector A selector can combine an element and an attribute. @Directive({ selector: 'button[appSave]', standalone: true }) export class SaveButtonDirective {} Matches <button appSave> Save </button> Does Not Match <a appSave> Save </a> The directive applies only to a button containing the appSave attribute. 6. Multiple Selectors A component or directive can support multiple selectors separated by commas. @Directive({ selector: ` [appTooltip], [data-tooltip] `, standalone: true }) export class TooltipDirective {} Both Match <button appTooltip> Help </button> <button data-tooltip> Help </button> Use multiple selectors carefully because they increase the number of ways the directive can be applied. Selector Matching Happens Statically Angular matches selectors when it compiles the template. Changing an attribute dynamically at runtime does not cause Angular to create a new component or directive instance. Example @Directive({ selector: '[appAdmin]', standalone: true }) export class AdminDirective {} <div [attr.appAdmin]="isAdmin ? '' : null"> Admin Area </div> This runtime attribute binding does not dynamically attach or remove the directive. The directive must be present statically in the template: <div appAdmin [class.active]="isAdmin" > Admin Area </div> Selector Case Sensitivity Angular selectors are case-sensitive. selector: 'app-user-card' Correct <app-user-card></app-user-card> Incorrect <app-User-Card></app-User-Card> Component Selector Best Practice Use custom element selectors with a meaningful prefix. Recommended: app-user-card app-order-list admin-dashboard store-product Avoid: user card header button Generic names may conflict with standard HTML elements or other libraries. Directive Selector Best Practice Use camelCase attribute selectors for directives. Recommended: [appHighlight] [appAutofocus] [appPermission] [appTooltip] Usage: <input appAutofocus /> <button appPermission> Delete </button> Selector vs Template Reference Variable Selector Template Reference Variable Matches components or directives References an element, directive, or component instance Defined in metadata Defined in the template selector: 'app-user' #userComponent Controls creation or application Provides template access Example <app-user #userComponent ></app-user> Here: app-user is the component selector #userComponent is a template reference variable Selector vs CSS Selector Angular selector syntax looks similar to CSS selectors, but it is used for component and directive matching rather than styling. Angular Selector CSS Selector Creates a component or applies a directive Applies styles Defined in Angular metadata Defined in a stylesheet Matched during template compilation Matched by the browser styling engine Common Selector Examples Selector Matches app-header <app-header> [appHighlight] Any element containing appHighlight .app-special Any element with class app-special input[type="email"] Email input elements button[appSave] Buttons containing appSave Common Mistakes 1. Using a Selector That Conflicts with HTML Avoid: selector: 'button' selector: 'header' selector: 'input' Prefer unique custom-element names. 2. Forgetting to Import a Standalone Component A selector is not available automatically. The component or directive must be imported where it is used. @Component({ selector: 'app-dashboard', standalone: true, imports: [ UserCardComponent ], template: ` <app-user-card /> ` }) export class DashboardComponent {} 3. Using Invalid Selector Casing Avoid: selector: 'AppUserCard' Prefer: selector: 'app-user-card' 4. Using Dynamic Attributes to Attach Directives Angular selector matching is static. Attribute bindings do not dynamically create directive instances. 5. Using Complex Selectors Unnecessarily Prefer simple and predictable selectors that make template usage easy to understand. Best Practices Use element selectors for components Use attribute selectors for directives Use a unique project or library prefix Use kebab-case for component selectors Use camelCase for directive attribute selectors Avoid selectors that conflict with native HTML elements Keep selectors short, meaningful, and consistent Avoid overly complex selector combinations Remember that selector matching occurs statically Interview Questions What is an Angular selector? An Angular selector is a template pattern that tells Angular where to create a component or apply a directive. Where is a selector defined? A selector is defined in the metadata of @Component() or @Directive() . What selector type is recommended for components? A custom element selector such as app-user-card is recommended for components. What selector type is recommended for directives? An attribute selector such as [appHighlight] is recommended for directives. Can Angular attach a directive when an attribute is added dynamically? No. Angular matches selectors statically while compiling the template. Dynamically adding an attribute does not create a new directive instance. Can a directive have multiple selectors? Yes. Multiple selectors can be separated by commas, although this should be used only when necessary. Why should selectors use a prefix? A prefix reduces naming conflicts and identifies which application or library owns the component or directive. Key Point Selectors connect Angular components and directives with the HTML patterns where they should be used. Easy Formula Component Selector = Custom HTML Element Directive Selector = HTML Attribute Element Selector = app-user-card Attribute Selector = [appHighlight] Combined Selector = button[appSave] Template Element ↓ Selector Match ↓ Component or Directive Created ↓ Angular Behaviour Applied