Search code examples
angularevent-binding

Angular : Event binding not "permanent"


Consider the following code from my AppComponent that I am using to learn Angular.

import { Component } from '@angular/core';

@Component({
  selector: 'root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title: string = 'Trade Assist';
  tabs = Tabs.tabs;
  selectedTabId?: number;
  constructor(){}
  onTabClick(selectedTabId : number){  
    console.log(selectedTabId);
    this.selectedTabId = selectedTabId;
  }
}


<div class="root">
    <div class="header">
        <div class="heading">{{title}}</div>
        <div class="navbar">
            <ul>
                <li class="li-l" (click)="onTabClick(1)"><a href="">AAAA</a></li>
                <li class="li-l" (click)="onTabClick(2)"><a href="">BBBB</a></li>
            </ul>
        </div>
    </div>
    <div class="body">
        <ng-container *ngIf="selectedTabId==1"><p>{{selectedTabId}}</p></ng-container>
        <ng-container *ngIf="selectedTabId==2"><p>{{selectedTabId}}</p></ng-container>
    </div>
</div>

When I click on the <li> element, I see the 1 or 2 that was returned by the event for for a split second in the <p> element. It doesn't remain there. Also the console logging comes and goes... What on earth am I doing wrong?


Solution

  • I think what is causing the issue here is the <a href=""> element. once you click on the navigation link it will shortly print the desired result as you observed, but then will reload the page which will reset the selectedTabId back to undefined.

    what you could do is replace the anchor tag or remove the href attribute.

    <div class="navbar">
      <ul>
         <li class="li-l" (click)="onTabClick(1)"><span>AAAA</span></li>
         <li class="li-l" (click)="onTabClick(2)"><span>BBBB</span></li>
      </ul>
    </div>
    

    incase you want to add routing to the <li> element you can still do so by using the angular routerLink to the element. Additionally you will need to import the RouterModule inside your app.module.ts in the imports array like this.

    // app.module.ts
    imports: [
      RouterModule,
      ....
      ]
    
    // app.component.html
    <li class="li-l" routerLink="/route" (click)="onTabClick(1)"><span>AAAA</span></li>