Cannot create property 'selectedTest' on string 'test1' - problem with Angular

走远了吗. 提交于 2020-01-06 14:20:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!