Search code examples
angularangular2-templateangular2-ngfor

Binding a logout method in angular


I am trying to bind a logout function to a menu item that is being populated dynamically, When someone clicked logout it signs out the user. I have tried the follow code but seems not to be working.

Here is my component.ts file

usermenu: Object[] = [ {
    icon: 'tune',
    route: '/dashboard/settings',
    title: 'Account settings'
  }, {
    icon: 'exit_to_app',
    route: '',
    title: 'Sign out',
    method: 'logout()'
  },
];

logout(){
  //my code
}

My template.html

  <md-nav-list>
    <a *ngFor="let item of usermenu" [routerLink]="item.route" md-list-item (click)="item.method" ><md-icon>{{item.icon}}</md-icon>{{item.title}}</a>
  </md-nav-list>

For example when I click on account setting it redirects to setting comment, which is simple in this case. For signing out it won't be a component but a method which I have created logout(). Am looking on way I can bind it to the route when clicked it will log the user out.


Solution

  • Take a look here:

    http://plnkr.co/edit/UWLgn5B6ADLc26mgHWDb?p=info

    I modified:

    usermenu: Object[] = [ {
        icon: 'tune',
        route: '/dashboard/settings',
        title: 'Account settings',
    method: ()=>{}
      }, {
        icon: 'exit_to_app',
        route: '',
        title: 'Sign out',
        method: this.logout
      },
    ];
    

    And in the template:

    <a *ngFor="let item of usermenu" [routerLink]="item.route" md-list-item (click)="item.method()" >
              <md-icon>{{item.icon}}</md-icon>
              {{item.title}}
            </a>
    

    So basically you have to add a default arrow function for every link that dont have an operation, I think that inst really smart, but it works.