首页 > 解决方案 > ionic 4 通过单击按钮填充列表

问题描述

我有一个从数组生成列表的页面。我从网上得到了这个例子。其中显示html代码输出键一和键2。(1)我想修改代码以仅输出键一。我该如何修改代码来做到这一点?(2) 如果我想使用按钮单击来输出键一或键二,我该怎么做?这是代码:

messages = [{
    'One' : [
    {'id' : 1},
    {'id' : 2},
    ],
   'Two' : [
    {'id' : 1},
    {'id' : 2},
   ]
 }] ;


 @Component({
 ...
 })
 export class YourComponent{
 objectKeys: any = Object.keys;
 messages: Array<any>;

 out(key){

 }
 constructor(){}

 ...
 }


HTML:
<ion-button (click)="out('one')">button 1 </ion-button>
<ion-button (click)="out('two')">button 2 </ion-button>


<div *ngFor="let message of messages">
  <div *ngFor="let key of objectKeys(message)">
    <div>KEY: {{ key }}</div>
    <div *ngFor="let val of message[key]">{{ val.id }}</div>
</div>

OUTPUT:
 KEY: One
      1
      2
 KEY: Two
      1
      2

标签: angularjshtmlionic4

解决方案


我通过在 html 代码中使用 ngIf 找到了 (1) 的解决方案。这是工作代码:

<div *ngFor="let message of messages"> 
   <div *ngFor="let key of objectKeys(message)">
   <div *ngIf="key=='One' ">
       <div>KEY: {{ key }}</div>
       <div *ngFor="let val of message[key]">{{ val.id }}</div>
   </div>
   </div>
</div>

推荐阅读