Preventing Redundancy in Angular 2: Tips for Avoiding Duplicate Methods

Is there a way I can streamline my if/else statement to avoid code repetition in my header component? Take a look at the example below:

export class HeaderMainComponent {
logoAlt = 'We Craft beautiful websites'; // Logo alt and title texts

@ViewChild('navTrigger') navTrigger: ElementRef;

isMenuShown: false;

constructor(private layoutService: LayoutService, private renderer) { }

menuToggle(event: any) {
    this.toggleNavClass();
}

onMenuSelect(event: any) {
    this.isMenuShown = false;
    this.toggleNavClass();
}

private toggleNavClass() {
    if (this.navTrigger.nativeElement.classList.contains('opened')) {
        this.navTrigger.nativeElement.classList.remove('opened');
    } else {
        this.navTrigger.nativeElement.classList.add('opened');
    }
}
}

Answer №1

Wouldn't it make sense to go about it like this?

export class HeaderMainComponent {
logoAltText = 'We specialize in creating stunning websites'; // Alternate text for the logo

@ViewChild('navTrigger') navTrigger: ElementRef;

isMenuVisible: false;

constructor(private layoutService: LayoutService, private renderer: Renderer) { }

toggleMenu(event: any) {
    if (this.navTrigger.nativeElement.classList.contains('opened')) {
        this.navTrigger.nativeElement.classList.remove('opened');
    } else {
        this.navTrigger.nativeElement.classList.add('opened');
    }
}

selectMenuItem(event: any) {
    this.isMenuVisible = false;

    this.toggleMenu(event); // Make sure to include the event binding
}

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Scrolling to a specific position on a page when a Vue 3 component appears is a must-do for

When I click a button, my basic form component appears without using the router. I would like the scroll position of the form to automatically move down slightly (for example, on the y-axis at 40) once it is displayed. However, I am unsure of how to achi ...

"Problems with the YouTube API functions: playVideo, pauseVideo, and stopVideo not

Currently, I am working on integrating the YouTube API to control a group of players within a slideshow. My goal is to pause and play videos based on which slide the slideshow is on. I have tried storing the players in an array using the frame's id. W ...

Manipulate the visibility of a child element's dom-if based on a property retrieved from the parent element

Exploring the world of Polymer, I am eager to tackle the following scenario... I have a binding variable called {{readonly}} that sends data from a parent Dom-HTML to a child Dom-HTML in my Polymer project. The code excerpt looks something like this... C ...

Receiving and monitoring events triggered by a Vue component that was dynamically mounted

I am currently mounting a Vue component dynamically within a mixin to incorporate the resulting HTML into a map popup. While everything is functioning correctly, I am facing an issue with listening to events emitted by the component. I am unsure of how to ...

Using regular expressions to identify the presence of "&", parentheses, and consecutive letters in a string

I specialize in working with JavaScript and I have a need to verify if my text contains certain characters. Specifically, I want to check for the presence of parentheses (), ampersands (&), and repeating letters within the text. Here are some examples: te ...

I encountered an issue where TypeScript's generics function was unable to locate a property within an interface

I am attempting to define a function in typescript using generics, but I encountered the following error: "Property 'id' does not exist on type 'CustomerInterface'" This occurs at: customer.id === +id getCustomer<Custo ...

Ways to eliminate the initial digit of a decimal number if it is less than 1

I need assistance with modifying float values by removing the first number if it's lower than 1 In the "OPS" table section, I am calculating the sum of OBP and SLG obtained from a database. See the code snippet below: <td>{props.player.OBP}< ...

Flip an image by analyzing the colors beneath it

Looking for a way to invert the color of specific areas under a mask (PNG) for a floating menu. Rather than inverting all at once, I want only certain parts to be inverted underneath the mask. Is this achievable, or is there another approach I should consi ...

Tips for presenting retrieved HTML unchanged within an Angular 2 template

Currently, I am fetching post data from a remote server. The content of the posts includes HTML with style and class attributes which are generated by a WYSIWYG editor. My goal is to display the HTML data as it is, without any filtering or sanitization. ...

Tips for dynamically implementing a pipe in Angular 5

In my Angular application, I have implemented a filter using a pipe to search for option values based on user input. This filter is applied at the field level within a dynamically generated form constructed using an ngFor loop and populated with data from ...

Tally up identical words without considering differences in capitalization or extra spaces

Let's take an example with different variations of the word "themselves" like "themselves", "Themselves", or " THEMSelveS " (notice the leading and trailing spaces), all should be considered as one count for themselves: 3 ...

What is the best way to integrate functions using an interface along with types?

Currently, I am working on a school project that requires me to develop a type-safe LINQ in Typescript using advanced types. I am facing a challenge in figuring out how to ensure all my tables (types) can utilize the same interface. My goal is to be able ...

Using Moment JS to display the days of the upcoming week

I'm in the process of developing a weather application and I need to create code that will display the upcoming week's weather forecast. The only information I have from the server is a "time" entity with a "value" set for next Monday such as "20 ...

"Is there a way to extract a value from a JSON object using

I have an object with the following key-value pairs: { 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier': '918312asdasc812', 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name': 'Login1&a ...

Calculating the sum of all words that have been successfully finished

My spelling game includes words of different sizes ranging from 3 to 6 letters. Once a certain number of words are completed in the grid, the remaining grid fades away. Instead of only considering one word size at a time, I want the game to calculate the t ...

Issue with the code: Only arrays and iterable objects are permitted in Angular 7

Trying to display some JSON data, but encountering the following error: Error Message: Error trying to diff 'Leanne Graham'. Only arrays and iterables are allowed Below is the code snippet: The Data {id: 1, name: "Leanne Graham"} app.compone ...

What steps should I follow to create a JavaScript file incorporating jQuery?

As a newcomer to JavaScript and JQuery, I come from a background in basic C++ where I enjoy including header files and calling functions from there to maintain clean code. Now that I want to create a new JavaScript file, how can I ensure that I am able to ...

How can a Vue component interact with a JavaScript method?

Within my main.js file, I have configured Vue as follows: window.Vue = require('vue'); Vue.component('my-component', require('./components/MyComponent.vue')); const app = new Vue({ el: '#app', }); Additionall ...

Looking to scan through a directory of .html files in Node.js to find specific element attributes?

Imagine trying to tackle this task - it's like reaching for a needle in a haystack. Picture a folder containing a static website, complete with images, stylesheets, and HTML files. My Node application needs to dive into this folder and extract only th ...

Set up a JavaScript function that triggers an alert if two numbers are determined to be equal

I created a code snippet that should display an alert message when a button is clicked, indicating whether two random numbers generated are equal or not. The random numbers must be integers between 1 and 6. I implemented this functionality in JavaScript bu ...