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

Make the text stand out by highlighting it within a div using a striking blue

Currently, I am working with Angular2 and have incorporated a div element to display multiple lines of text. Positioned below the text is a button that, when clicked, should select the entirety of the text within the div (similar to selecting text manually ...

What is the best way to include numerous optional parameters within a single route in Express?

Been a huge fan of Stackoverflow and finally decided to ask my first question here! I've been working on a JavaScript Express project, trying to figure out if it's possible to achieve the desired functionality under a single GET request. Struggli ...

A guide to exporting a PDF in A4 size landscape mode with jspdf

As a novice in UI development, I am currently trying to export HTML content to PDF using the JSPDF library. However, I have encountered difficulties in generating the PDF in A4 size landscape mode. The HTML code includes data with charts (canvasjs/chartjs) ...

Utilize the ref attribute when working with Material UI InputLabel components

Is there a way to access the ref parameter of an InputLabel from the @material-ui/core library using TypeScript? When I attempt to do so, the following code produces an error related to ref: TS2769: No overload matches this call. export class ComboBo ...

Exploring Mikro-ORM with Ben Awad's Lireddit: Navigating the Process of Running Initial Migrations

Having some trouble following the lireddit tutorial, particularly with the initial mikro-orm migration step. Encountering a similar issue as mentioned in this post. Tried modifying the constructor of the example entity (tried both provided format and the ...

The echo statement is failing to show any value following the ajax request

I am in need of assistance. I would like to output the value from a PHP echo statement using an AJAX call. Currently, the code is functioning without any errors. When I select options from a dropdown menu, the value is displayed on the console by using con ...

Updating state with new data in React: A step-by-step guide

Recently, I delved into the world of reactjs and embarked on a journey to fetch data from an API: constructor(){ super(); this.state = {data: false} this.nextProps ={}; axios.get('https://jsonplaceholder.typicode.com/posts') ...

The Azure DevOps pipeline is indicating that the global CLI version is higher than the local version you have on

I'm currently facing an issue while trying to deploy an Angular front end to Azure pipeline from GitHub using yaml. The problem occurs during the npm build and install stage, with an error message stating 'Your global Angular CLI version (15.2.6) ...

What steps can I take to stop Highcharts from showing decimal intervals between x-axis ticks?

When the chart is displayed, I want to have tick marks only at integer points on the x-axis and not in between. However, no matter what settings I try, I can't seem to get rid of the in-between tick marks. Chart: new Highcharts.chart('<some i ...

JavaScript-based tool for extracting content from Sketch file

My goal is to extract the contents of a .sketch file. I have a file named myfile.sketch. When I rename the file extension to myfile.zip and extract it in Finder, I can see the files inside. However, when I try the same process on the server using Node.js ...

The Angular 4 framework is a powerful tool for web development, offering

While attempting to iterate over an array, I noticed that the DOM is displaying [ object Object] instead of the desired information. Some sources suggested using Stringify to display the info, but it's not possible to iterate over a string. Any assist ...

The trouble with dynamicHelpers in Nodejs Express

Trying to make my app run smoothly, I've set up the following configurations: app.configure(function(){ app.set('views', __dirname + '/views'); app.enable('jsonp callback'); app.set('view engine', 'j ...

Implement seamless content loading using jQuery, eliminating the need

Is there a reason why this piece of code isn't working for me? I'm trying to load HTML content using jQuery and followed the instructions from this tutorial: Here's how my HTML looks: <div id="icon"> <a href="http://localhost/ ...

Adjust the dimensions of the dropdown menu

Objective: How can I adjust the width of a select dropdownlist that is utilizing bootstrap v2? Challenge: I am uncertain about how to modify the width in the context of bootstrap. Additional Information: Keep in mind that there are three dropdownli ...

Is there any way to deactivate the saved query in react-admin without having to develop a new component?

The latest version of react-admin, version 4, introduced a new feature that allows saving filters. I'm curious about how to disable this functionality without having to create an additional filter button. https://i.stack.imgur.com/uTrUe.gif ...

What is the best way to generate a variable amount of div elements with constantly changing content using Angular2?

I'm not entirely sure on the process, but I believe ngFor would be used in this scenario. Essentially, my goal is to generate the following div multiple times, with each iteration updating the value inside the brackets from 0 to 1, 2, and so forth... ...

What is the best way to utilize TypeScript module augmentation with material-ui components?

I have gone through the answers provided in this source and also here in this link, but it appears that they are outdated. I attempted to enhance the type definition for the button component in various ways, including a separate typings file (.d.ts) as we ...

The Typescript Decorator is triggered two times

I submitted a bug report regarding Typescript because I suspect there is an issue, although I'm seeking additional insights here as well. This is the scenario. When running the following code: class Person { @IsValueIn(['PETER', ' ...

Determine the total of the final column in recently added rows by utilizing JavaScript

I have a table where users can dynamically add rows as needed. I am looking to implement a feature that will display the total of the last column in a text box underneath the table using JavaScript. If real-time calculations are not feasible, then I am ope ...

Guide to adding sound effects to your Vue 3 app using the Composition API

I'm having trouble setting up a basic button click feature in Vue 3 Composition API to play a sound effect. In my setup function, I have imported an mp3 sound effect from the assets folder and passed it into a ref method with an HTMLAudioElement type, ...