Reputation: 335
I have some code that I am working on, that allows a user to pick a contact, I want the code to be able to populate an array,
as that then populates the Html template with NgFor
However, I am battling to make the function change data in the array dynamically could anyone help me or at least point me into a direction.
here is the relevant code html file
<ion-list>
<ion-grid>
<ion-row>
<ion-col>
<ion-item-group (click) = "pickContact()" *ngFor="let contacts of mContacts">
<ion-card>
<ion-item lines = "none">
<ion-label class="ion-text-wrap">Name: {{contacts.name}}</ion-label>
</ion-item>
<ion-item lines = "none" >
<ion-label class="ion-text-wrap">Number: {{contacts.number}}</ion-label>
</ion-item>
</ion-card>
</ion-item-group>
</ion-col>
</ion-row>
</ion-grid>
</ion-list>
I want the function pickContact to be called when the card is selected and then populate the corrosponding element in the array. ts file
export class ContactComponentComponent implements OnInit {
constructor(private contacts: Contacts) { }
mContacts = [
{
name: [''],
number: ['']
},
{
name : ['Carl'],
number: ['065 623 4567']
}
];
ngOnInit() {}
//currently thows an error:
//Property 'name' does not exist on type '{ name: string[]; number: string[]; }[]'.
//Property 'number' does not exist on type '{ name: string[]; number: string[]; }[]'
pickContact() {
this.contacts.pickContact().then((contact) => {
this.mContacts.name = contact.name.givenName;
this.mContacts.number = contact.phoneNumbers[0].value;
});
}
}
Upvotes: 0
Views: 4473
Reputation: 181
You should update you data like that, it is easier..
mContacts = [
{
name: '',
number: '',
},
...
];
You need to put your pickContact function inside ion-card with an the contact object to know exactly which contact you wanna pick.
let contacts --> let contact (it is one contact)
<ion-item-group *ngFor="let contact of mContacts">
<ion-card (click)="pickContact(contact)">
<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-card>
</ion-item-group>
Then in you component
...
pickContact(contact) {
this.contacts.pickContact().then((contacts) => {
contacts.forEach(c => {
if (c.name === contact.name ) {
// Do the matching
const contactToUpdate = mContacts.find(c => c.name === contact.name)
contactToUpdate.name = c.name;
contactToUpdate.number = c.number;
}
})
});
}
I dont see exactly the use case here but this is something you can do.. There are of course better way to do it but I prefer keeping it simple.
One thing about this
name: [''] --> This is an array of string so to get the value, you need to do mContacts[0].name[0] --> You'll get the first item of the array and log his name but I dont understand why you have an array here...
You could use lodash to do some stuff Lodash
Hope I could help
Upvotes: 2