liveBook · Manning

Selector property

As explained in Pro Angular 16

An Angular directive selector is metadata that specifies which elements or attributes cause a directive to be applied.

The `selector` property tells Angular which HTML elements a component or directive applies to. It is a CSS selector in `@Component` or `@Directive` metadata. For a component, a matching element becomes its host, and Angular places the component’s template content there. section 2.3.3 section 16.2.1

Match a component to its host

A component configured with `selector: "app"` needs a matching `<app></app>` element. If you change the selector from `app-root` to `app`, change the element in `index.html` too. `templateUrl: "template.html"` identifies the content Angular puts in that host; it does not choose the host. section 9.6.2

When adding components to an application:

  • Declare each new component in the Angular module so Angular can use it. section 16.2.1
  • Add matching host elements where the components should appear. For example, `<paProductForm>` and `<paProductTable>` in a parent template match their respective component selectors. section 16.2.1
Listing 17.2. Changing the selector in the cellColor.directive.ts file in the src/app folder
import { Directive, HostBinding } from "@angular/core";
 
@Directive({
    selector: "td[paApplyColor]"
})
export class PaCellColor {

    @HostBinding("class")
    bgClass: string = "";

    setColor(dark: Boolean) {
        this.bgClass = dark ? "table-dark" : "";
    }
}

The directive selector `td[paApplyColor]` shows that matching can depend on both an element and an attribute. Changing it to an attribute absent from the HTML stops the table-cell coloring directive from applying. section 17.1

How Pro Angular 16 covers it

How deep it goes
Explains selector-to-host matching through component setup and a directive change, without detailing selector parsing.
Examples
Shows `app-root` and `app` hosts, nested form and table components, and a `td[paApplyColor]` directive selector.
What it assumes
Assumes basic HTML and TypeScript familiarity while introducing decorator metadata and component host matching.
What you can do after
Operate/configure it by matching a selector to an HTML host or changing a selector to prevent a directive from applying.
How it connects
Connects CSS selectors with decorators, host elements, component templates, directives, and Angular module declarations.

Also explained in

Compare how 2 books explain selector property →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pro Angular 16. The section links point to the parts of the book it draws on.