Home > Software engineering >  Can we overwrite existing html component with same name component in Angular?
Can we overwrite existing html component with same name component in Angular?

Time:07-02

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

CodePudding user response:

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.

  • Related