我有一个从数组生成列表的页面。我从网上得到了这个例子。其中显示html代码输出键1和键2.(1)我想修改代码只输出Key 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
我在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>
我通过使用ng-if和ng-model提出解决方案(1)和(2)以下是代码:
html :
<ion-button (click)="out('one')">button 1 </ion-button>
<ion-button (click)="out('two')">button 2 </ion-button>
<ion-input type="hidden" [(ngModel)] ='nameFilter' ></ion-input>
<div *ngFor="let message of messages">
<div *ngFor="let key of objectKeys(message)">
<div *ngIf="key==nameFilter ">
<div>KEY: {{ key }}</div>
<div *ngFor="let val of message[key]">{{ val.id }}</div>
</div>
</div>
</div>
ts code :
@Component({
...
})
export class YourComponent{
objectKeys: any = Object.keys;
messages: Array<any>;
nameFilter: String = 'one';
out(key){
if (key == 'one') {
nameFilter = 'one';
}
else {
nameFilter = 'two';
}
}
constructor(){}
...
}