要将表单值与数组值进行映射,可以使用Angular的双向数据绑定和表单控件的ngModel指令。
首先,在组件类中定义一个数组和一个表单变量,用于存储数组值和表单值:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
- {{ item }}
`,
styleUrls: ['./app.component.css']
})
export class AppComponent {
items: string[] = ['Item 1', 'Item 2', 'Item 3'];
newItem: string = '';
addNewItem() {
this.items.push(this.newItem);
this.newItem = '';
}
}
在上述代码中,我们通过ngFor指令循环显示数组中的每个元素,并使用ngModel指令与表单控件进行双向绑定。当用户输入表单值时,数组值也会随之更新。
点击"Add Item"按钮时,会调用addNewItem()方法,将newItem的值添加到items数组中,并重置newItem的值为空。
最后,通过ngFor指令循环显示数组中的每个元素,并将其显示在界面上。
以上代码示例演示了如何将表单值与数组值进行映射,并在界面上实时更新。