我想要有多个活动按钮(如果选中),当我单击所选按钮时,我想删除活动类(切换)。我怎样才能做到这一点?如果我这样做,我有错误:
ERROR TypeError: Cannot create property 'selectedTest' on string 'test1'
HTML
<div class="btn-group">
<div class="btn btn-outline-secondary" *ngFor="let test of tests" (click)="selectTest(test)"
[ngClass]="{active: isActiveTest(test)}">
{{test}}
</div>
</div>
TS
import { Component } from '@angular/core';
@Component({
selector: 'test',
templateUrl: './test.html',
styleUrls: ['./test.scss'],
})
export class TestComponent {
tests: any;
constructor() {
this.tests = ['test1', 'test2', 'test3']
}
ngOnInit() {
}
selectTest(item) {
item.selectedTest = !item.selectedTest;
};
isActiveTest(item) {
return item.selectedTest;
};
}
问题在于你的物品。你是循环数组,其中包含字符串值,当你想选择 - > selectTest(item)时,你提供的是一个字符串值,它不是一个Object类型而且没有参数'selectedTest',你应该改变你的数组包含对象列表:
this.test = [
{ value: 'test1', isSelected: false },
{ value: 'test1', isSelected: false },
{ value: 'test1', isSelected: false }
];
还将selectTest函数更改为:
selectTest(item) {
item.isSelected = !item.isSelected;
};
然后在html中更改:
<div class="btn-group">
<div class="btn btn-outline-secondary" *ngFor="let test of tests"
(click)="selectTest(test)"
[ngClass]="{ 'active': test.isSelected }">
{{test.value}}
</div>
</div>