4

Is it possible to add a directive programmatically to all elements in a component with a given class name, possibly using

document.getElementsByClassName("btn")

I want to add the matRipple directive to all elements that use the btn class without requiring our team to manually add the directive to every element.

Or is there another way I am missing to apply an Angular Material directive to elements of a given class or tag name (e.g. button)

Note that this is intended for legacy apps where we do not want to switch them all to mat-buttons. The directive works fine, but I am looking for a way to make it easier for our devs.

Steve
  • 14,401
  • 35
  • 125
  • 230
  • Why not just do search and replace once? – waterplea Mar 15 '19 at 16:47
  • I was looking for a piece of JS i could add so that my devs would not need to do that. Just curious, as that would be the obvious solution but require them to do something. – Steve Mar 15 '19 at 16:54

1 Answers1

3

Or is there another way I am missing to apply an Angular Material directive to elements of a given class or tag name (e.g. button)

Yes, you may declare a selector to be based on a tag, attribute, class and so on. For a class, you would define it as: '.class'.

You may find all options on the docs

GCSDC
  • 3,138
  • 3
  • 28
  • 48
  • This is good to know, but would require me to make code changes to the directive itself. While I could do that for my own directives, I don't want to edit Angular Material's source code. Unless I misunderstand... – Steve Mar 18 '19 at 12:54
  • You're right @Steve. Missed that you were using a third party directive. I've tried to create a custom directive to wrap matRipple directive and insert it programatically, but it seems not to be possible so far. [This answer](https://stackoverflow.com/a/43752424/6481438) points to a github request for that and provides an alternative (not sure if this is suitable for this use case). Also, should I delete this answer so? – GCSDC Mar 18 '19 at 20:34
  • No, your answer might help someone else. Thanks for the link! – Steve Mar 19 '19 at 00:30