问题
I want to have multiply active buttons (if selected), and when I click on selected button, I want to remove active class (toggle). How can I do this? If I do it like below, I have error:
ERROR TypeError: Cannot create property 'selectedTest' on string 'test1'
hmtl
<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;
};
}
回答1:
problem is with your item. You are looping array which contains string values and when you want to select -> selectTest(item), you are providing a string value, which isn't a Object type and doesn't have param 'selectedTest', you should change your array to contain a list of Objects:
this.test = [
{ value: 'test1', isSelected: false },
{ value: 'test1', isSelected: false },
{ value: 'test1', isSelected: false }
];
also change selectTest function to:
selectTest(item) {
item.isSelected = !item.isSelected;
};
then in html change:
<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>
来源:https://stackoverflow.com/questions/52210735/cannot-create-property-selectedtest-on-string-test1-problem-with-angular