如何使用ngFor

时间:2019-05-16 03:52:43

标签: node.js angular typescript ngfor

每次单击模块扩展面板时,都会对该API进行HTTP调用,以使所有公司可用于该特定模块。

  <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响应(可用的公司):

{
  "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" }
  ]
}

我的问题:

在每个模块扩展面板的内部,我想显示可用的公司作为清单。但是我在访问对象的键值并为每个复选框进行迭代时遇到了麻烦。到目前为止,这是我尝试过的:

      <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>

我认为也许我需要改变使用按键管道或ngFor的方式?任何帮助或想法都会很棒,谢谢:)

其他信息:

这是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) 跟踪单击的模块/垂直。 如果扩展了两个模块(信用卡和存款),则this.companies将存储module_names(密钥)和每个公司的可用数组:

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

1 个答案:

答案 0 :(得分:0)

您正尝试使用keyvalue,但语法错误

除非您有自定义管道声明,否则您需要使用 keyvalue ,而不仅仅是 keys

<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>