我有一个正在开发的应用程序,目前我正在开发一个部分,用户可以在该部分中点击标有“紧急联系人”的项目。然后向用户呈现一个包含 5 个空 block 的列表,每个 block 都有一个标签 姓名: 编号:
用户点击一个 block ,然后选择一个联系人。
目前,我可以使用用户从联系人列表中选择的姓名和号码填充其中一个 block 。
这是相关代码
import { Component, OnInit } from '@angular/core';
import { Contacts, Contact, ContactField, ContactName } from '@ionic-native/contacts/ngx';
@Component({
selector: 'app-contact-component',
templateUrl: './contact-component.component.html',
styleUrls: ['./contact-component.component.scss'],
})
export class ContactComponentComponent implements OnInit {
constructor(private contacts: Contacts) { }
ngOnInit() {}
cName:any;
cNumber:any;
pickContact() {
this.contacts.pickContact().then((contact) => {
this.cName = contact.name.givenName;
this.cNumber = contact.phoneNumbers[0].value;
// console.log(cNumber);
});
}
}
这是hmtl 重复 5 次得到 5 个 block
<ion-grid>
<ion-row>
<ion-col>
<ion-item-group (click) = "pickContact()">
<ion-card>
<ion-item lines = "none">
<ion-label class="ion-text-wrap">Name: {{cName}}</ion-label>
</ion-item>
<ion-item lines = "none" >
<ion-label class="ion-text-wrap">Number: {{cNumber}}</ion-label>
</ion-item>
</ion-card>
</ion-item-group>
我的问题是,如果没有成堆的代码,我不知道如何重复这个。
我正在考虑使用嵌套数组,但我完全不确定如何去做 我希望用户点击一个 block -> 选择一个联系人 -> 函数填充相应的 block 。
有什么建议吗?
最佳答案
Angular 在处理列表方面表现出色。事实上,您不必对整个列表进行硬编码。
您需要的是 *ngFor 指令。
.html 文件
<ion-card *ngFor="let contact of emergencyContacts; let i=index">
<ion-item-group (click)="pickContact(i)">
<ion-item lines = "none">
<ion-label class="ion-text-wrap">Name: {{contact.name}}</ion-label>
</ion-item>
<ion-item lines = "none" >
<ion-label class="ion-text-wrap">Number: {{contact.number}}</ion-label>
</ion-item>
</ion-item-group>
</ion-card>
.ts 文件
export class ContactComponentComponent implements OnInit {
/*
of course, the following array would be better to be created by a loop
I leave it this way to be easier to understand
*/
emergencyContacts = [
{name: '', number: ''},
{name: '', number: ''},
{name: '', number: ''},
{name: '', number: ''},
{name: '', number: ''}
]
constructor(private contacts: Contacts) { }
ngOnInit() {}
pickContact(i) {
this.contacts.pickContact().then((contact) => {
this.emergencyContacts[i].name = contact.name.givenName;
this.emergencyContacts[i].number = contact.phoneNumbers[0].value;
});
}
}
关于javascript - ionic /Angular 如何将数据添加到列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58268157/