Home > OS >  Angular.js: Cannot set a custom attribute directive
Angular.js: Cannot set a custom attribute directive

Time:02-14

I have ultra-simple code with a directive and a component trying to use it but the code doesn't work. Cannot understand what I am doing wrong.

@Directive({
  selector: '[classSetter]'
})
class classSetter implements OnInit {
  
  @Input() classSetter : string = "";

  el : ElementRef;

  constructor (el : ElementRef) {
    this.el = el;
  }

  ngOnInit () {
    this.el.nativeElement.classList.add(this.classSetter);
  }
}

@Component({
  selector: 'app-root',
  styles: ['.blue {background-color: blue;}'],
  template: `
              <span [classSetter]="'blue'">{{title}}</span>
            `
})
export class AppComponent {
  title = 'directive';
}

The error I get is Can't bind to 'classSetter' since it isn't a known property of 'span'.

StackBlitz: https://stackblitz.com/edit/angular-ivy-gf1ee4

Please, tell me, what do I miss here?

CodePudding user response:

The directive needs to go in declarations array of module not the providers array of component decorator. fixed it here as well :-

https://stackblitz.com/edit/angular-ivy-bz2sez?file=src/app/app.component.ts

  • Related