Issue with Angular: RouterLinkActive fails to work properly with formControlName

I am currently working on a vertical navigation bar that allows the user to navigate to different components. However, I am facing an issue where when I click on a list item, it's supposed to be active but I have to click on it to navigate to the component and then click on the same navigation for it to become active.

Important Note: The routerLinkActive does not seem to be functioning ONLY when I added formControlName="name" to the form. The routerLinkActive works fine when I remove it.

Can someone please help me identify what mistake I am making?

nav.component.html

<nav>
    <ul class="side-nav">
        <li routerLinkActive="active" tabIndex="1">
            <a routerLink="/profile-details">Profile Details</a>
        </li>

        <li routerLinkActive="active" tabIndex="1">
            <a routerLink="/profile-address">My Address</a>
        </li>

        <li routerLinkActive="active" tabIndex="1">
            <a routerLink="/profile-card">My Cards</a>
        </li>

        <li routerLinkActive="active" tabIndex="1">
            <a routerLink="/profile-password">Change Password</a>
        </li>

        <li routerLinkActive="active" tabIndex="1">
            <a routerLink="/settings">Account Settings</a>
        </li>

        <li routerLinkActive="active" tabIndex="1">
            <a routerLink="/privacy">Consent & Privacy</a>
        </li>
    </ul>
</nav>

nav.component.css

.active {
    background-color: rgb(255, 255, 255) !important;
    border-left: 8px solid rgb(0, 185, 173);
}

profile-details.component.html

<div class="profile">
    <div class="row">
        <!-- Profile Nav -->
        <div class="col-3">
            <app-nav></app-nav>
        </div>

        <div class="col-5 details">
            <h2>Profile Details</h2>

            <form class="form">
                <div class="form-group">
                    <h6>Name: </h6>
                    <input type="text" id="name" name="name" formControlName="name" class="form-control" />
                </div>

                <button type="submit" class="btn btn-primary btn-lg">Save</button>
            </form>
        </div>
    </div>
</div>

app-routing.module.ts

const routes: Routes = [
  { path: 'profile', component: NavComponent },
  { path: 'profile-details', component: ProfileDetailsComponent },
  { path: 'profile-address', component: ProfileAddressComponent },
  { path: 'profile-card', component: ProfileCardComponent },
  { path: 'profile-password', component: ProfilePasswordComponent },
  { path: 'settings', component: SettingsComponent },
  { path: 'privacy', component: PrivacyComponent }

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Answer №1

Do you have a formGroup set up in your code? It appears that in order to use formControlName, you need to have a reactive control implemented, which doesn't seem to be the case in your current code.

I'm referring to having something defined as a formGroup in your code, similar to this example:

profile-details.component.ts

import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
...

export class ProfileDetailsComponent implements OnInit {
  form: FormGroup;
  ....

  constructor(
    private fb: FormBuilder,
    ...
  ) {...}

  ngOnInit(): void {

    this.form = this.fb.group({
      name: [''],
...
    });

}

profile-details.component.html

<form [formGroup]="form">
   <div class="form-group">
      <h6>Name: </h6>
      <input type="text" id="name" name="name" formControlName="name" class="form-control" />
   </div>
   <button type="submit" class="btn btn-primary btn-lg">Save</button>
</form>

Lastly, don't forget that when using reactive forms, you need to import ReactiveFormsModule in your module (usually in app-routing.module.ts):

import { ReactiveFormsModule } from '@angular/forms';  
@NgModule({  
imports: [  
 // other imports ...  
ReactiveFormsModule  
 ],  
})  
export class AppModule { }

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

Concealed Separator for Text Elements in HTML

I am in search of a method to distinguish certain specific strings within HTML code. Although I can recognize the desired strings, they may also appear as part of longer strings throughout the document. In order to locate them, I currently insert a special ...

"What is the best way to use jQuery to create a toggle effect where one button controls the state

I'm looking to improve the efficiency of my code, but I'm not sure where to start in terms of making it more concise and organized. Any suggestions on how to streamline this code and keep it neat would be greatly appreciated. $(document).ready(fu ...

Header Dropdown Problems

Hey there, I have a question regarding my header setup. I currently have two headers in place: Whenever I click the notification button, the dropdown menu seems to disrupt the layout of the header. Here is a screenshot for reference: Below is the CSS cod ...

Creating a Button with Icon and Text in TypeScript: A step-by-step guide

I attempted to create a button with both text and an icon. Initially, I tried doing it in HTML. <button> <img src="img/favicon.png" alt="Image" width="30px" height="30px" > Button Text ...

Click on the button to convert the content of the text area into a variable

Is there a way to capture all the text inside a textarea or input field as a variable upon button click using jQuery or JavaScript? The .select() function doesn't seem to achieve this, instead displaying numerous CSS properties when logged. What app ...

Can I integrate @types/pkg into my custom library to automatically have types included?

Imagine I am creating a library that utilizes types from the Definitely Typed repository (such as @types/pkg). Would it be feasible for my package to automatically include these types when installed, eliminating the need for consumers to separately instal ...

How can a default value be assigned to an ag-Grid filter?

Is there a way to set a default value in ag-grid filter text that is displayed to the user but not applied to the actual results? this.columnDefs = [ { headerName: this.pageData["tbm.line.list.grid.phonenumber"], field: 'tn', /*sor ...

Trouble arises in AWS Code Pipeline as a roadblock is encountered with the Module

After many successful builds of my Angular project, it suddenly fails to build on AWS Code Build. I reverted back to a commit before any recent changes, but the error persists. When I run ng build --prod locally, it works fine. However, during the pipeline ...

Safari displays text in a noticeably bigger font size compared to other browsers

I'm currently working on a website and have noticed that the fonts appear larger on Mac's Safari compared to other browsers. We are using the 'Open Sans' font from Google Fonts for our website. For example, here is a CSS snippet for ti ...

The readyState of Ajax is consistently anything but 4

I have encountered an issue with my JavaScript code. I am running these codes in order to display data based on user input. Despite there being no error connection and the connection happening properly, whenever I enter a name it always goes into the else ...

Loop through items in a list using Angular.js and display each item within an <

I am facing an issue where the model returned from the server contains html tags instead of plain text, such as b tag or i tag. When I use ng-repeat to create a list based on this model, the html is displayed as pure text. Is there a filter or directive av ...

Vue: The enigmatic world of ghost properties?

During my project work, I encountered the following code snippet: Main component - <ParameterModal>: <template> <modal-wrapper props="..."> <!-- ... other similar templates are present... --> <template v-else-if="moda ...

Assigning a value using HTML code causes the input to malfunction

Trying to create a website with the goal of updating the database is proving to be challenging. The issue lies in the fact that some attributes from the database are in HTML format. Whenever I attempt to set an input's value to match the current attri ...

Managing the combination of <a href/> and <br/> tags simultaneously

I'm working on a website that features details similar to those shown in the image: https://i.sstatic.net/tws1D.png Below is the HTML content: <div class="tableholder"> <br> <br> Open <a href="javascript:popWin1('/ASCNA/s ...

What is the best way to prevent or highlight a particular row in a table depending on the line number values using Angular 2 and NgFor?

My work involves using angular2 and dealing with a table of games. I have a list of games in the database that have been clicked on before (each game can be clicked once). I want to add a class (whether it's a block or painted it doesn't matter) ...

Guide on populating text boxes in a form automatically using ngFor?

As a beginner Angular developer, I am looking to automatically fill in text boxes in a form, specifically 10 text boxes (10 rows) using the ngFor directive. In my research on ngFor examples, I have noticed that most of them focus on populating a list base ...

Importing custom pipes in Angular 2 becomes a bit tricky when working with data grouping

As a newcomer to Angular JS, I have recently started using Angular 2 for a project of mine. Here is an example of my JSON data: "locations": [ { "id": "ASS", "name": "test center", "city": "Staten Island", "zip": ...

Transfer information from session to vue-component

Within my routes file, I obtain the current user from the session and then render the profile HTML: app.get('/profile', isLoggedIn, function(req, res) { res.render('profile.html', { user : req.user // extract user ...

Generic interface function in Typescript

Having some issues with my generic interface function. Seems like I've been staring at it for too long... Can someone please point out what I'm doing wrong? This is my Interface: export interface Compareable<T> { equals(compareable:T) ...

What are the best practices for managing global data in an Angular application?

Embarking on the journey to learn Angular 4 and ASP Net Core 2 simultaneously, I have decided to build a blog application. As I progress, I find myself in need of storing global data that can be accessed by every component. For instance, I aim to pass the ...