Angular 如何动态更改数组中的值

Angular How to dynamically change a value from an Array

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

然后用 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;
    });
  }

}

你应该这样更新你的数据,这样更容易..

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

您需要将您的 pickContact 函数放入带有联系人对象的 ion-card 中,以准确知道您想要选择哪个联系人。

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

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

}

我看不到这里的具体用例,但这是你可以做的事情。当然有更好的方法,但我更喜欢保持简单。

有一件事

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

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

希望能帮到你