html - 使用javascript将类添加到数组中的元素
问题描述
问题陈述:有一个引导列表组。“活动”类突出显示列表组中的选定项目。在加载组件(角度)时,应该预先选择几个列表项,这是我面临的问题。
HTML代码如下:
<div class="list-group" *ngFor="let role of roles | filter : searchText">
<a id="{{role}}" class="list-group-item list-group-item-info list-group-item-action" (click)="selectRole(role)">
{{ role }}
</a>
</div>
ts文件如下:
roles = ["Admin", "Developer", "Tester", "Production Support", "Marketing", "Admin1", "Developer1", "Tester1", "Production Support1", "Marketing1", "2Admin", "2Developer", "2Tester", "2Production Support", "2Marketing"]
selectedRoles = ["Developer", "Marketing"]
userForm = this.fb.group({
name: [''],
roles: this.fb.array([])
})
ngOnInit( ): void {
this.patchRole()
console.log(this.userForm.value)
}
patchRole(){
console.log('patch value')
this.userForm.patchValue({roles: this.selectedRoles});
let elements = document.getElementsByClassName('list-group-item')
console.log(elements)
for (let i=0; i<this.roles.length; i++){
for (let j=0; j<this.selectedRoles.length; j++){
if (this.roles[i] === this.selectedRoles[j]){
elements[i].className += ' ' + "active"
}
}
}
}
你能帮忙吗?
解决方案
我会使用ngClass为列表项设置正确的类。
见:https ://stackblitz.com/edit/angular-ivy-qhzmeb
<div class="list-group" *ngFor="let role of roles">
<a id="{{role}}" class="list-group-item list-group-item-info list-group-item-action" (click)="selectRole(role)"
[ngClass]="{'active': isSelected(role) }">
{{ role }}
</a>
</div>
然后实现一个检查角色是否被包含的函数。
export class AppComponent {
fb = new FormBuilder()
roles = ["Admin", "Developer", "Tester", "Production Support", "Marketing", "Admin1", "Developer1", "Tester1", "Production Support1", "Marketing1", "2Admin", "2Developer", "2Tester", "2Production Support", "2Marketing"]
selectedRoles = ["Developer", "Marketing"]
userForm = this.fb.group({
name: [''],
roles: this.fb.array([])
})
ngOnInit( ): void {
this.patchRole()
console.log(this.userForm.value)
}
selectRole(role) {
let pos = this.selectedRoles.indexOf(role);
if (pos === -1) {
this.selectedRoles.push(role);
} else {
this.selectedRoles.splice(pos, 1);
}
}
isSelected(role) {
return this.selectedRoles.includes(role);
}
patchRole(){
console.log('patch value')
this.userForm.patchValue({roles: this.selectedRoles});
}
}
推荐阅读
- string - 对目录中的文件执行操作,它们不以某个字符串开头
- asynchronous - 如何让 Redux Saga 运行同步代码
- php - Woocommerce 设置发货方式,获取运费
- python - Python海龟bgpic瞬间消失
- c - cuda和矩阵运算中的Grid-Stride Loop,我们为什么需要它?
- sql - 显示日期是工作日还是周末的 SQL Server 过程
- react-native - 与 Redux 一起使用的 React-Native 最佳导航解决方案
- c++ - 使用 Sublime Text 3 在 Powershell 中构建 C++ 而不是 CMD
- html - 防止两个引导容器相互重叠。?
- javascript - 为什么有些函数需要在函数名之前声明“函数”?