Home > OS >  Angular : Event binding not "permanent"
Angular : Event binding not "permanent"

Time:01-19

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 >
    <div >
        <div >{{title}}</div>
        <div >
            <ul>
                <li  (click)="onTabClick(1)"><a href="">AAAA</a></li>
                <li  (click)="onTabClick(2)"><a href="">BBBB</a></li>
            </ul>
        </div>
    </div>
    <div >
        <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?

CodePudding user response:

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 >
  <ul>
     <li  (click)="onTabClick(1)"><span>AAAA</span></li>
     <li  (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  routerLink="/route" (click)="onTabClick(1)"><span>AAAA</span></li>
  • Related