简体   繁体   中英

Angular: Using javascript Object.somefunction() in ngFor

I have an ngFor iterating on keys generated by Object.keys() as follows:

    <ul id='nav-tablist' class='tabrows'>
        <li *ngFor="let tab of obj.keys(tabList)">
            <a class="{{ tabList[tab].active?'tab-selected':''}}" 
                rel="{{ tab }}" (click)="tabClicked($event)">{{ tabList[tab].title }}
            </a></li>

'obj' is defined in the component as follows: obj: Object = Object;

The code works but I get an error during the compile cycle (not cool but the code is generated and works fine). I tried using Object.keys() directly and that erred and didn't work at all. So, is there a better way to do this (iterate over a set of keys inside ngFor)? Here is a sample of what 'tabList' looks like:

  tabList: {
    [key: string]: {
      rdoKey: string,
      title: string,
      active: boolean,
      onClose?(): void,
      onActivate?(): void
    } 
  } = {
    "tab-1": { rdoKey: null, title: 'Info', active: true, onClose: function(){}, onActivate: function(){} },
    "tab-2": { rdoKey: null, title: 'Data Tab 1', active: false, onClose: function(){}, onActivate: function(){} }
  };

Thanks,

Use the KeyValuePipe : https://angular.io/api/common/KeyValuePipe

<ul id="nav-tablist" class="tabrows">
  <li *ngFor="let tab of tabList | keyvalue">
    <a class="{{ tab.value.active?'tab-selected':''}}" rel="{{ tab.key }}" (click)="tabClicked($event)">{{ tab.value.title }}
    </a>
  </li>
</ul>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM