组件代码示例:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
jsonData = [
{ name: 'Item 1' },
{ name: 'Item 2' },
{ name: 'Item 3' }
];
selectOption = '';
addOption() {
if (this.selectOption !== '') {
this.jsonData.push({ name: this.selectOption });
this.selectOption = '';
}
}
}
HTML模板代码示例:
JSON 数据
-
{{ item.name }}
选择选项
这个示例中,我们首先定义了一个jsonData
数组来存储JSON数据,以及一个selectOption
变量来存储选择选项。在HTML模板中,我们使用*ngFor指令来循环遍历jsonData
数组,并使用ngModel指令将选择选项的值绑定到selectOption
变量。然后,我们使用一个按钮来触发addOption()
方法,该方法将选择选项的值添加到jsonData
数组中。