Guide on making an active link the default setting upon the initial loading of a page with Angular 2

import {Component, Input, Output, EventEmitter, OnInit, AfterContentInit} from 'angular2/core';
import {FORM_DIRECTIVES, NgFor} from 'angular2/common';
import {MenuService} from './menu.service';
import {OrderByPipe} from '../shared/pipes/OrderBy';

declare var $: any;

@Component({
 selector: 'category',
 directives: [FORM_DIRECTIVES, NgFor],
 providers: [
    MenuService
 ],
 pipes: [OrderByPipe],
 template: `
    <div class="category-list" data-spy="affix" data-offset-top="20" id="nav2"> 
     <span class="category-list-item" *ngFor="#item of items | orderBy :['sort_order']"
        (click)="change(item)"
        [ngClass]="{'active':item.active}">
        <a id="elementID">{{item.name}}</a>
     </span>
 </div>

`
})

export class CategoryComponent implements OnInit, AfterContentInit {
@Input() items:any;
@Output('change') changeEmitter: EventEmitter<any> = new EventEmitter();

change(item:any): void {
    this.items.map((o:any)=> { o.active=false;});
    item.active = true;
    this.changeEmitter.emit(item);
    $('html, body').animate({
        scrollTop: 0// $('#elementID').offset().top + 200
    }, 300);
}
ngOnInit() {
    // this.items.map((o:Object)=> { o.active=false;});
    // this.items[0].active=true;
        $('#nav2').affix({
            offset: { top: 100 }
        });
}
ngAfterContentInit() {
            // Component content has been initialized
    // console.log(this.items);
  }
}


[![current behavior of nav link][1]][1]

https://i.sstatic.net/0ptLy.png

I am utilizing Angular 2 for my product listing page. I have successfully implemented a feature to change the background color of a link after clicking on it. However, I am facing an issue regarding the default active state of the first link when the page is initially loaded.

Answer №1

A helpful tip for initializing item properties can be found in the ngOnInit function:

ngOnInit() {
  this.items.forEach((item:any)=> { item.active = false; });
  if (Array.isArray(this.items) && this.items.length > 0) {
    this.items[0].active = true;
  }
}

Remember to always verify that this.items is defined and it's actually an array before manipulating its elements.

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

Utilizing Apex charts within the Angular 9 framework

I am encountering an issue with utilizing apex charts in angular 9. I can successfully display the chart (line chart) when using mocked data as shown in the first screenshot, but I am facing difficulties when trying to fetch data from a REST API – the ch ...

Transforming react.js into HTML and CSS programming languages

I have a small experiment I need help with. As I am not familiar with react.js, I would like to convert my main.jsx file into pure HTML/CSS/JS without using react. The issue I'm facing is how to handle form data submission to the server in vanilla HTM ...

How can I retrieve data submitted in a POST request on my Node.js server

I'm having trouble sending form data to a node/express server using AJAX. After submitting, I keep getting redirected to a 'Cannot POST /' page. Although I can log the request object on the server side, the data from the form is missing. Wha ...

Tips for creating an onChange function in an input field using jQuery

I am looking to dynamically create inputs where each input has an `onChange` function with a variable. Here is my code: var distinct_inputs = 0; $('.icon1').click( function(){ distinct_inputs = distinct_inputs + 1 ; $('#insert-file&apo ...

`The challenge of a single web page not displaying correctly`

I was working on a website for a local computer building company, and I decided to make it a single-page applet. The HTML is mostly done, and I don't have much trouble with CSS. However, I encountered an issue with hiding and displaying different sect ...

What is the mechanism behind the workings of the requestAnimationFrame loop?

I'm currently studying the ins and outs of javascript and Three.js but I'm struggling to grasp the concept of how the requestAnimationFrame function operates. Could someone please break down the following code in simple terms for me? ( feel free ...

Creating a Route in Angular 2 for a Component other than the one initialized with the bootstrap function

I am currently in the process of working on a project involving Angular2. If you are interested in understanding why I need to do what I am about to explain, please take a look at this issue. The main component in my project is called AppComponent and it ...

Using JQuery Slider to call a function without the need for an ID, instead utilizing the object directly

Currently, I am working on implementing a Slider using JQuery, and I have encountered an issue in my code. The function is set to run when the page loads, creating a slider with the Id specified in the div element: $(function() { $( "#slider& ...

What is the best way to manage data in a single-page application and retrieve it after the page has been refreshed?

Lately, I’ve encountered an issue with data storage in a single-page application. I’m seeking some guidance on how to effectively store data and retain it after refreshing the page within a Single Page Application. As an example, let's say I hav ...

Is it possible for ng-repeat to change the index of an internal collection while reordering?

In my code, I am working with an array of objects: $scope.widgets = [{ col: 0, name: "Tile 1" }, { col: 1, name: "Tile 2" }, { col: 2, name: "Tile 3" }]; Each object from the array is displayed as a widget within a grid. When usin ...

The Vue/Nuxt application displays content duplication on each page, rendering the content twice without duplicating the components

I recently delved into Vue/Nuxt programming and worked through a tutorial on adding a blog, which I then customized for my website. Everything functions perfectly except that the content is rendering twice. It goes from rendering NavPage (component) > c ...

Exploring the differences in two date variables using Angular

Is it possible to compare these two dates directly or should I convert one of them first? date1: 2019-07-31T23:00:00 date2: Fri Aug 30 2019 00:00:00 GMT+0100 (West Africa Standard Time) I am using Angular for this task. ...

The AXIOS method in Express.js is designed to return a Promise object that may contain an

I am currently learning ExpressJS and Axios I have created a folder named utils and placed the axios.js file const axios = require('axios'); loadDataPesan=async function(opts){ axios.get('localhost/getData', { params ...

Pass a PHP string to a JavaScript function using AJAX

Recently, I encountered an issue with my database storing email content. To retrieve this content, I made an ajax request and wanted to pass the data to a function that would display a popup with the email content. However, the email content contains HTML ...

What could be causing the preloader to fail in my React application?

I am developing a React App with Redux functionality, and I am looking to implement a preloader when the user clicks on the "LoginIn" button. To achieve this, I have created a thunk function as follows: export const loginInWithEmail = (email, password) =&g ...

The specified data type is not compatible with the current context and cannot be treated as an array

Just starting out with TypeScript and I've encountered an issue that's preventing me from successfully building my app. Everything runs smoothly on my local environment, but as soon as I try to build it, an error pops up. Here's a snippet o ...

What is the best way to access the CSS font-size property using JavaScript?

I've attempted to adjust the font size using this code: document.getElementById("foo").style.fontSize Unfortunately, this code does not return any results. The CSS styles are all defined within the same document and are not in an external stylesheet ...

Learn how to access nested arrays within an array in React using TypeScript without having to manually specify the type of ID

interface UserInformation { id:number; question: string; updated_at: string; deleted_at: string; old_question_id: string; horizontal: number; type_id: number; solving_explanation:string; ...

What sets apart using `: Interface` versus `as Interface` in Typescript?

I'm struggling to find the distinction between two similar lines of code due to uncertainty about what they are called. Consider the scenario where the following interface is defined: interface Person { name: string; age: number; } What exactly ...

Enhancing your react-slick carousel with a captivating full-screen background

I need assistance with implementing a full screen slider using react-slick. I am facing difficulty in adding an image as the background. My code snippet looks like this: import image1 from "../assets/bg1.png" import image2 from "../ ...