Angular2 onclick in ngfor

时间:2017-05-24 18:11:50

标签: javascript angular ngfor

尝试在ngFor期间通过单击输出函数调用。我不确定如何引用它。

我是angualr2的新手,我不确定这是否是实现这一目标的正确方法。我很感激任何建议。

export class Navbar {

    constructor() {}

    public userNavs = [
        { title: 'Account', click: 'account()'  },
        { title: 'Logout', click: 'logout()'  }
    ]

    logout() {
        console.log('working');
    }

    account(){
        console.log('working');
    }

    ngOnInit() {}
}

////HTML////

<ul class="dropdown-menu dropdown-menu-right" aria-labelledby="userdropdown">               
    <li *ngFor="let nav of userNavs" ><a class="dropdown-item btn-sm" (click)="{{ nav.click }}" >{{ nav.title }}</a></li>
</ul>

1 个答案:

答案 0 :(得分:2)

这是一种更好的方法:

    export class Navbar {

    constructor() {}

    public userNavs = [
        { title: 'Account', click: 'account()'  },
        { title: 'Logout', click: 'logout()'  }
    ]

    eventClick(userNav){
      if('Account') this.account();
      else this.logout();
    }

    logout() {
        console.log('working logout');
    }

    account(){
        console.log('working account');
    }

    ngOnInit() {}
}

////HTML////

<ul class="dropdown-menu dropdown-menu-right" aria-labelledby="userdropdown">               
    <li *ngFor="let nav of userNavs" ><a class="dropdown-item btn-sm" (click)="eventClick(nav)" >{{ nav.title }}</a></li>
</ul>