简体   繁体   中英

Is it a good practice to change variable value directly from angular template

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"">

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 A ngular Style Guide best practices mentioned in the Angular Style Guide in Official Angular Documentation here .

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, eg
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">

Using a function in your component to handle the event and update the variable, like handleHover() , is a good practice because it keeps the component's template simple also for reusability, you can use the same handler again and it's better for testing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM