简体   繁体   中英

How to access key values from array object in Angular with ngFor

Every time a module expansion panel is clicked, a HTTP call is made to the API to get all the companies available to the particular module.

  <mat-accordion *ngIf="modules">
    <mat-expansion-panel *ngFor="let module of modules">
      <mat-expansion-panel-header (click)="availableCompanies(module.module_name)">
        <mat-panel-title>
          {{module.module_name}}
        </mat-panel-title>
      </mat-expansion-panel-header>

HTTP response (available companies):

{
  "message": "Retrieved companies available to module",
  "data": [
    { "co_code": "123", "name": "Company A" },
    { "co_code": "456", "name": "Company B" },
    { "co_code": "789", "name": "Company C" }
  ]
}

My Problem:

Inside each module expansion panel, I want to then display the available companies as a checklist. But I'm having trouble accessing the key values of the object and iterating for each checkbox. Here's what I've tried so far:

      <mat-list dense>
        <mat-list-item *ngFor="let vertical of companies | keys">
          <mat-checkbox *ngFor="let company of companies[vertical]">
            {{company.name}}
          </mat-checkbox>
        </mat-list-item>
      </mat-list>

I think maybe I need to change how I'm using the keys pipe or the ngFor? Any help or ideas would be awesome, thanks :)

Extra Information:

Here's the list.component.ts:

export class listComponent implements OnInit {
  @Input() modules: Module[];
  @Input() companies: Company[] = [];

  constructor(
    private rs: RecipientService, // has getAvailableCompanies http method
  ) { }

  ngOnInit() {
  }

  availableCompanies(vertical: string) {
   this.rs.getAvailableCompanies(this.recipient.email_address, vertical).subscribe(res => {
     this.companies[vertical] = res;
     console.log(res);
     console.log(this.companies);
   });
  }

}

console.log(res):

(3) [
     { "co_code": "123", "name": "Company A" }, 
     { "co_code": "456", "name": "Company B" }, 
     { "co_code": "789", "name": "Company C" }
    ]

console.log(this.companies) keeps track of modules/verticals clicked. If two modules have been expanded (credit_cards and deposits), this.companies stores the module_names (keys) and the array of companies available each:

[credit_cards: Array(3), deposits: Array(4)]

you are trying to use keyvalue but with wrong syntax,

you need use keyvalue not as just keys unless you have a custom pipe declaration.

<mat-list dense>
     <mat-list-item *ngFor="let vertical of companies | keyvalue">
         <mat-checkbox *ngFor="let company of companies[vertical]">
            {{company.name}}
         </mat-checkbox>
     </mat-list-item>
 </mat-list>

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