Reputation: 335
I have an APP that I am working on, at the moment I am working on a section where the user taps on an item that is labelled 'Emergency Contacts'. Then the user is presented a list of 5 empty blocks that each have a label name: number:
the user taps a block and then then selects a contact.
At the moment I can populate one of the blocks with the name and number the user selects from the contacts list.
here is the relevant code
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);
});
}
}
here is the hmtl which is repeated 5 times to make 5 blocks
<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>
my problem is I do not know how to repeat this, without having piles of code.
I was thinking of using a nested Array but I am not sure entirely how to go about it I want the user to tap on a block -> select a contact -> functions populates corresponding block.
any suggestions?
Upvotes: 0
Views: 878
Reputation: 2825
Angular is exceptional at handling lists. Indeed, you do not have to hardcode the whole list.
What you need is the *ngFor directive.
.html file
<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 file
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;
});
}
}
Upvotes: 1