1

I created an Angular component which has a navbar, which is created as an unformatted list. By clicking on a list element, I want to call a method from the component.ts, which changes the showed component within this component.

I am an absolute beginner to Angular and web development, so I need help to solve that.

I tried using button oncklick="methodcall()" and a href="methodcall()" in the list element, which both worked. But using a button changes the styling of my navbar icons and a link shows the function call in the uri. I don't want any of this side effects.

html:

<nav>
  <ul>
    <li onclick="switch('page1')">page1</li>
    <li onclick="switch('page2')">page2</li>
  </ul>
</nav> 

component.ts:

switch(propertyName: string) {
    ...
}

An easy way to call the method without changing my styling or the uri would be great!

3 Answers 3

3

You should be able to use (click) rather than onclick.

Something like this:

<nav>
    <ul>
      <li (click)="switch('page1')">page1</li>
      <li (click)="switch('page2')">page2</li>
    </ul>
</nav> 

Depending on how you are switching pages I would also consider using Angular Routing, it's incredibly powerful! Check it out.

Sign up to request clarification or add additional context in comments.

Comments

0

You need to put parentheses around the event to bind it.

Template/HTML:

<li (click)="switch('page1')">page1</li>

Component.ts:

export class ClickMeComponent {

  public switch(pageId: string) {
    // do something
  }
}

Here's the official Angular documentation about event binding: https://angular.io/guide/template-syntax#event-binding

Comments

0
<nav>
    <ul>
      <li (click)="switch('page1')">page1</li>
      <li (click)="switch('page2')">page2</li>
    </ul>
  </nav> 

Should work, but remember that it is actually not semantically correct, also for accessibility reasons I would always use a button or anchor for clicks. The styling for your icon can be kept in its original state by CSS. I would advise to do the following

<nav>
    <ul>
      <li>
        <button type="button" (click)="switch('page1')">
          <span class="icon"></span>
          <span class="label">page1</span>
        </button>
      </li>
      <li>
        <button type="button" (click)="switch('page2')">
          <span class="icon"></span>
          <span class="label">page2</span>
        </button>
      </li>
    </ul>
  </nav> 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.