0

I need to apply directive to button component. It is kind of this:

<button my-own-directive />

But the issue here is, in my application, there are many pages, and total button components can be hundreds in total.

I know I can do a global find and replacement, but that doesn't seem to be an elegant solution.

I am thinking if it is possible to extend current html button component and then apply the directive to the extended button. But here what I want is the extended button should also have the same name, so that I do not need to global search and replace.

Hope to hear your advice for this solutions, thanks

1
  • Dependency Injections maybe helpful here. Try reading more on useExisting/useClass provider Commented Jul 1, 2022 at 3:52

1 Answer 1

1

Technical answer :

You can create a directive with a simple button selector. Then directive will be activated for any button tag element.

custom-button.directive.ts :

@Directive({
  selector: 'button',
})
export class CustomButtonDirective implements OnInit {
  constructor(@Host() private button: ElementRef<HTMLButtonElement>) {}

  ngOnInit(): void {
    // do something with button
    // this.button.nativeElement...
  }
}

In html template :

<button (click)="..">My unchanged button</button>

Architecture advice :

Even if it's possible, I'm not sure it's a good practice or a good advice to give you. At first, it sounds great and very simple to activate new directive on all buttons with one source code, and one single import in app module for instance.

...but for maintenance of app, and future evolution, it could be a little nightmare, with unpredictable behavior. If someone else (or you in a few months...) add a new page with buttons, or would like a specific behavior.

Of course this comment is subjective and optional.

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

Comments

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.