离子/角度如何将数据添加到列表

时间:2019-10-07 10:56:32

标签: javascript angular typescript multidimensional-array ionic4

我有一个正在使用的APP,目前正在用户正在点击标有“紧急联系人”的项目的区域中进行操作。然后向用户显示5个空块的列表,每个空块都有一个标签  名称:  号码:

用户点击一个块,然后选择一个联系人。

enter image description here

此刻,我可以用用户从联系人列表中选择的名称和号码填充其中一个区块。

这是相关代码

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个方块

  <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>

我的问题是我不知道如何在没有大量代码的情况下重复此操作。

我当时在考虑使用嵌套数组,但是我不确定如何去做 我希望用户点击一个块->选择一个联系人->函数填充相应的块。

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

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;
          });
      }
}