Types of components selectors in Angular with examples

Type Selector

Selects are based on the HTML tag name. Example app-root. This type of selector you would be already familiar with as it is the default for all components in Angular.


@Component({
  selector: 'app-root',
  standalone: true,
  imports: [
    RouterOutlet,
    AttributeSelectorComponent,
    MultipleAttributeSelectorComponent,
    AttributeSelectorWithValueComponent,
    CssClassSelectorComponent
  ],
  templateUrl: './app.component.html',
  styleUrl: './app.component.scss',
})
export class AppComponent {

}

Attribute Selector

  • The selector property in the @Component decorator specifies the selector for the component. In this case, we're using an attribute selector [app-attribute-selector].
  • To use the directive, you add the app-attribute-selector attribute to any HTML element in your template.
  • The content within that element will be replaced by the template defined in the directive.
    import { Component } from '@angular/core';
    
    @Component({
      selector: '[app-attribute-selector]',
      standalone: true,
      imports: [],
      templateUrl: './attribute-selector.component.html',
      styleUrl: './attribute-selector.component.scss'
    })
    export class AttributeSelectorComponent {
    
    }
    

component view code

<p>attribute-selector works!</p>

Attribute selector with value

  • The selector property in the @Component decorator specifies the selector for the component. In this case, we're using an attribute selector [app-attribute-selector-with-value=” test”].
  • To use the directive, you add the app-attribute-selector-with-value=” test” attribute to any HTML element in your template.
  • The content within that element will be replaced by the template defined in the directive.
    import { Component } from '@angular/core';
    
    @Component({
      selector: '[app-attribute-selector-with-value="test"]',
      standalone: true,
      imports: [],
      templateUrl: './attribute-selector-with-value.component.html',
      styles: ``
    })
    export class AttributeSelectorWithValueComponent {
    
    }
    

component view code

<p>attribute-selector-with-value works!</p>

The selector with multiple attributes

  • The selector property in the @Component decorator specifies the selector for the component. In this case, we're using an attribute selector [app-multiple-attribute-selector="test"][is-active].
  • To use the directive, you add the app-multiple-attribute-selector="test" is-active attribute to any HTML element in your template.
  • The content within that element will be replaced by the template defined in the directive.
    import { Component } from '@angular/core';
    
    @Component({
      selector: '[app-multiple-attribute-selector="test"][is-active]',
      standalone: true,
      imports: [],
      templateUrl: './multiple-attribute-selector.component.html',
      styleUrl: './multiple-attribute-selector.component.scss'
    })
    export class MultipleAttributeSelectorComponent {
    
    }
    

component view code

<p>multiple-attribute-selector works!</p>

Key Points

  • Attribute selectors are useful when you want to apply a component to multiple elements based on a common attribute.
  • They are often used for directives that provide additional functionality to existing elements.
  • Attribute selectors are case-sensitive.

Note. For attribute values, Angular supports matching an exact attribute value with the equals (=) operator. Angular does not support other attribute value operators.

CSS Class Selector
 

Class selector

A CSS class selector is used to target elements that have a specific class attribute. The class attribute is defined within the opening tag of an HTML element and is preceded by a dot (.).

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

@Component({
  selector: '.app-css-class-selector',
  standalone: true,
  imports: [],
  templateUrl: './css-class-selector.component.html',
  styles: ``
})
export class CssClassSelectorComponent {

}

component view code

<p>css-class-selector works!</p>

:not pseudo-class

The: not pseudo-class in CSS allows you to target elements that do not match a specific selector. You can leverage this in Angular component selectors to create more targeted components.

Explanation

  • The :not(.disabled) part of the selector ensures that the component only matches elements with the class "container" that do not also have the class "disabled".
  • This provides a way to conditionally apply the component based on the presence or absence of other classes.
    import { Component } from '@angular/core';
    
    @Component({
      selector: '.app-css-not-pseudo-selector:not(.disabled)',
      standalone: true,
      imports: [],
      templateUrl: './css-not-pseudo-selector.component.html',
      styles: ``
    })
    export class CssNotPseudoSelectorComponent {
    
    }
    

component view code

<p>css-not-pseudo-selector works!</p>

Targeting elements that are not direct children of a specific element.

@Component({
  selector: 'div:not(.parent) > p'
})
export class MyComponent {
}

Targeting elements that do not have a specific attribute.

@Component({
  selector: 'button:not([disabled])'
})
export class MyButtonComponent {
}

Key Points

  • The :not pseudo-class can be combined with other selectors to create more complex targeting rules.
  • It's a powerful tool for creating reusable components that can be applied conditionally based on the structure of your HTML.
  • Be cautious when using :not with complex selectors, as it can sometimes lead to unexpected behavior if not used correctly.

By understanding and utilizing the : not pseudo-class, you can create more flexible and targeted components in your Angular applications.

Combining selectors

You can combine selectors in Angular using CSS-like syntax to create more specific targeting rules. Here are some examples.

You can combine with Element, class, id, pseudo-class, attributes, comma-separated selectors, and so on.

Combining by Element, Class, and ID

TypeScript
@Component({
  selector: 'div.container#my-container'
})
export class MyComponent {
}

This component will only match elements that are.

  • A div element
  • Have the class container
  • Have the ID my-container

Combining with Pseudo-Classes

TypeScript
@Component({
  selector: 'button:not(.disabled):hover'
})
export class MyButtonComponent {
}

This component will match buttons that.

  • Do not have the class disabled
  • Are being hovered over

Combining with Attributes

TypeScript
@Component({
  selector: '[data-type="product"][is-active]'
})
export class ActiveProductComponent {
}

This component will match elements that.

  • Have the attribute data type with the value "product"
  • Have the attribute is-active

Combining Multiple Selectors

You can combine multiple selectors using commas.

TypeScript
@Component({
  selector: '.container, .card'
})
export class MyComponent {
}

This component will match elements that have either the class container or the class card.

Remember

  • Specificity: The more specific your selector is, the higher its priority.
  • Cascading Stylesheets (CSS): If multiple selectors match an element, the most specific selector takes precedence.
  • HTML Structure: Ensure that your selectors match the structure of your HTML elements.

By effectively combining selectors, you can create targeted components that accurately match the elements you intend to interact with in your Angular application.

Below is the output of the Selectors explained above.

  • App.component.ts
    import { Component } from '@angular/core';
    import { RouterOutlet } from '@angular/router';
    import { AttributeSelectorComponent } from './attribute-selector/attribute-selector.component';
    import { MultipleAttributeSelectorComponent } from './multiple-attribute-selector/multiple-attribute-selector.component';
    import { AttributeSelectorWithValueComponent } from './attribute-selector-with-value/attribute-selector-with-value.component';
    import { CssClassSelectorComponent } from './css-class-selector/css-class-selector.component';
    import { CssNotPseudoSelectorComponent } from './css-not-pseudo-selector/css-not-pseudo-selector.component';
    import { CombiningSelectorsComponent } from './combining-selectors/combining-selectors.component';
    
    @Component({
      selector: 'app-root',
      standalone: true,
      imports: [
        RouterOutlet,
        AttributeSelectorComponent,
        MultipleAttributeSelectorComponent,
        AttributeSelectorWithValueComponent,
        CssClassSelectorComponent,
        CssNotPseudoSelectorComponent,
        CombiningSelectorsComponent
      ],
      templateUrl: './app.component.html',
      styleUrl: './app.component.scss',
    })
    export class AppComponent {
      show = false;
      testId = 'main-cta';
      title = 'angular-dev-test';
    }
    
  • component view code
    @if(show){
    <button [attr.data-test-id]="testId">Show CTA</button>
    } @else {
    <button [attr.data-test-id]="testId">Normal CTA</button>
    }
    
    <div app-attribute-selector is-active>will be ignored</div>
    <div app-attribute-selector-with-value="test">will be ignored</div>
    <div app-multiple-attribute-selector="test" is-active>will be ignored</div>
    <div class="app-css-class-selector">will be ignored</div>
    <div class="app-css-not-pseudo-selector">will be ignored</div>
    <button type="reset">Reset</button>

Page Output

Output


Similar Articles