Angular如何从数组动态更改值

时间:2019-10-07 16:39:23

标签: javascript arrays angular typescript ionic4

我正在处理一些代码,允许用户选择联系人,我希望代码能够填充数组,

然后用NgFor填充HTML模板

但是,我正在努力使函数动态更改数组中的数据 谁能帮助我,或者至少可以指出我的方向。

这是相关代码 html文件

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

我希望在选择卡片时调用pickContact函数,然后在数组中填充相应元素。 ts文件

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

}

1 个答案:

答案 0 :(得分:2)

您应该像这样更新数据,这很容易。

mContacts = [
  {
    name: '',
    number: '',
  },
  ...
];

您需要将pickContact函数放在带有接触对象的离子卡内,以准确了解您要选择的联系人。

让联系人->让联系人(是一位联系人)

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

然后在您的组件中

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

}

我在这里看不到用例,但这是您可以做的。当然有更好的方法,但是我希望保持简单。

这件事

名称:['']->这是一个字符串数组,因此要获取值,您需要执行 mContacts [0] .name [0] ->得到数组的第一项并记录他的名字,但我不明白为什么你在这里有一个数组...

您可以使用lodash做一些事情Lodash

希望我能帮忙