springbo
springbo

Reputation: 1096

css selector in angular directive

Looking at the documentation for angular directives they list valid selectors. https://angular.io/api/core/Directive

  1. element-name: Select by element name
  2. .class: Select by class name.
  3. [attribute]: Select by attribute name.
  4. [attribute=value]: Select by attribute name and value.
  5. :not(sub_selector): Select only if the element does not match the sub_selector.
  6. selector1, selector2: Select if either selector1 or selector2 matches.

But the only selectors that seems to work in a directive for me is 3 and 6.

Here is a stackblitz where I try to select .test css class in a directive and it doesn't work. https://stackblitz.com/edit/angular-css-class-selector-in-directive

What am I missing?

Upvotes: 0

Views: 2184

Answers (1)

Ashot Aleqsanyan
Ashot Aleqsanyan

Reputation: 4453

Please have a look at the working example. https://stackblitz.com/edit/angular-css-class-selector-in-directive-xqwriz

you need to register your directive into declaration in app.module.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppComponent, ComponentWithCssSelector, CssClassDirective } from './app.component';

@NgModule({
  imports:      [ BrowserModule, FormsModule ],
  declarations: [ AppComponent, ComponentWithCssSelector, CssClassDirective],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

Upvotes: 2

Related Questions