I have a variable in the component:
showModal: boolean
And this in the template:
<div (mouseover)="handleHover('hover')">
handleHover()
changes the value of showModal
.
Should I use a handleHover()
type func and point (mouseover)
to it or is it fine to do something like this?
<div (mouseover)="this.showModal = true"">
CodePudding user response:
When it comes to angular it's better to keep the template simpler as much as possible if you are following the template-driven-forms
approach. I assume you are following the template-driven forms approach. Therefore it's better to do the assignment via the component itself.
Either way is fine but for the sake of consistency and clean maintainable code, I would encourage you to follow handleHover()
type function and point (mouseover)
event to the particular function and do the rest.
For further clarity on these Angular issues I would strongly recommend following the Angular Style Guide best practices mentioned in the Angular Style Guide in Official Angular Documentation here.
CodePudding user response:
Personally I would argue it is fine, and even preferable, to assign directly to the showModal
variable in the template in the case that the only purpose of handleHover()
is to set the variable showModal
.
When reading the template, it is clear to see that only one simple assignment takes place, whereas using a function introduces the small overhead of needing to consult the .ts
file to understand what is happening. It also then completely bypasses the need to have handleHover()
at all (imagine how this would scale if you needed handlePrimaryBtnHover()
, handleSecondaryBtnHover()
, handleSecondaryBtnClick()
etc if all these functions are doing is updating a single variable).
This is minor though and the handleHover()
approach is definitely not bad of course.
I would say that handleHover()
may be preferred when
- It contains >1 lines of code, e.g.
handleHover() {
this.showModal = true;
this.showModalSubject.next(this.showModal)
}
- The function needs to be referenced in many different places in the same template (although I still think
showModal = true
is more readable/succint for this use case) - You want to explicitly test a TypeScript method that handles the assignment of
showModal
Note: you do not need to include this
when referencing variables from the template
<div (mouseover)="showModal = true">