Cannot create property 'selectedTest' on s

2019-08-19 08:26发布

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条回答
Lonely孤独者°
2楼-- · 2019-08-19 09:26

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>
查看更多
登录 后发表回答