您可以使用ngModel将值插入数组的解决方法如下所示:
HTML模板:
- {{item}}
组件代码:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
- {{item}}
`
})
export class AppComponent {
newItem: string;
items: string[] = ['Item 1', 'Item 2', 'Item 3'];
addItem() {
if (this.newItem) {
this.items.push(this.newItem);
this.newItem = '';
}
}
}
该示例中,我们首先在模板中使用双向绑定[(ngModel)]将输入框的值与组件中的newItem
属性进行绑定。然后当点击“Add Item”按钮时,调用addItem()
方法将newItem
的值插入到items
数组中,并将newItem
重置为空字符串。
在ngFor
指令中,我们使用*ngFor="let item of items"
将items
数组中的每个元素渲染到标签中。
请注意,为了使用ngModel
指令,您需要在AppModule
中导入FormsModule
模块,并将其添加到imports
数组中。