以下是使用Angular向列表中添加元素并以图形方式选择它的示例代码:
在app.component.html文件中,添加以下代码:
选择元素示例
-
{{item.name}} - {{item.color}}
在app.component.ts文件中,添加以下代码:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
items: { name: string, color: string }[] = [];
newItemName = '';
newItemColor = '';
selectedItemIndex = -1;
addItem() {
const newItem = { name: this.newItemName, color: this.newItemColor };
this.items.push(newItem);
this.newItemName = '';
this.newItemColor = '';
}
selectItem(index: number) {
this.selectedItemIndex = index;
}
}
在app.component.css文件中,添加以下代码:
.selected {
background-color: #ccc;
}
这个示例中,有一个表单用于添加新的元素到列表中。表单中有两个输入框,用于输入元素的名称和颜色。当点击添加按钮时,addItem()方法会被调用,将新的元素添加到items数组中,并清空输入框。列表中的每个元素都有一个点击事件,当点击某个元素时,selectItem()方法会被调用,将选中的元素的索引保存到selectedItemIndex变量中。使用CSS样式将被选中的元素高亮显示。