angularviewchildangular15

ViewChild in component vs passing in element from HTML


In my Angular 15 application, when I hit the Save button, I need to close the dialog. The dialog is only used in one location in the code...in the save event. So I can do it one of two ways:

  1. Add an @ViewChild for the dialog in the TS file and access that in the save method.
  2. Pass the dialog element to the save event handler from the HTML.

Is there an advantage of one vs. the other?


Solution

  • Both approaches are valid and can work, but each has its own advantages and disadvantages.

    Approach 1: Adding a @ViewChild for the dialog in the TS file and accessing it in the save method.

    Advantages:

    Disadvantages:

    Approach 2: Passing the dialog element to the save event handler from the HTML.

    Advantages:

    Disadvantages: