要解决这个问题,你可以使用Angular的双向绑定以及事件绑定来实现。以下是一个示例代码:
HTML模板:
选择选项
-
{{ option }}
已选择的选项
-
{{ selectedOption }}
组件代码:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
options: string[] = ['选项1', '选项2', '选项3', '选项4'];
selectedOptions: string[] = [];
selectOption(option: string) {
// 根据是否已选择,添加或移除选项
if (this.selectedOptions.includes(option)) {
this.selectedOptions = this.selectedOptions.filter(item => item !== option);
} else {
this.selectedOptions.push(option);
}
}
}
在上述代码中,我们使用*ngFor
指令动态绑定选项列表,并使用(click)
事件绑定在用户点击选项时触发selectOption
方法。在selectOption
方法中,我们根据选项是否已选择,添加或移除选项。已选择的选项将在另一个
元素中显示。
这样,当用户点击选项时,选项会被添加到已选择的选项列表中,再次点击则会从列表中移除。这个解决方案利用了Angular的双向绑定和事件绑定来实现动态选择选项。