问题陈述:有一个引导列表组。 “活动”类突出显示列表组中的所选项目。在加载组件(以角度)时,应预先选择几个列表项,否则我将遇到问题。
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});
}
}