【问题标题】:How to access key values from array object in Angular with ngFor如何使用 ngFor 从 Angular 中的数组对象中访问键值
【发布时间】:2019-05-16 03:52:43
【问题描述】:

每次单击模块扩展面板时,都会对 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) 跟踪点击的模块/垂直。 如果扩展了两个模块(credit_cards 和 deposit),this.companies 存储 module_names(键)和每个可用的公司数组:

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

【问题讨论】:

标签: node.js angular typescript ngfor


【解决方案1】:

您正在尝试使用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>

【讨论】:

    猜你喜欢
    • 2016-06-02
    • 2020-10-23
    相关资源
    最近更新 更多