0

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?

7
  • Have you provided the directive in provider array either in module or component? Commented Feb 13, 2022 at 14:02
  • Yes. And even tried to mention classSetter in imports: [...] of AppComponent where I use it. And still same error. Commented Feb 13, 2022 at 14:50
  • can you please provide me with a stackblitz with this code and issue Commented Feb 13, 2022 at 15:02
  • Have you tried this; <span classSetter [classSetter]="'blue'"> . Since you have to bind to the input property not the directive itself. Commented Feb 13, 2022 at 15:07
  • Thank you so much for your time! Aakash Garg, tried your suggestion and got the same result. Faith Ersoy, here it is! stackblitz.com/edit/angular-ivy-gf1ee4 Commented Feb 13, 2022 at 15:46

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

That's right! Thank you so much! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.