我想在此选择(星级选择)一门课程。但它是for循环所以一旦我点击就会选择

时间:2017-01-19 11:33:47

标签: angular typescript

enter image description here

在图片中,我点击后所有课程都被选中,但我只想选择一门课程(带星级)

import {Component} from 'angular2/core'
import{CourseService} from './course.service'

@Component({
    selector: 'courses',
    template: `   

    <h2>Courses</h2>
    {{title}}
    <ul>
        <li *ngFor="#course of courses; #index=index">
            <a (click)="onClick()">
                <span>
                    <i class="glyphicon"
                        [class.glyphicon-star-empty]="!isFavorite"
                        [class.glyphicon-star]="isFavorite"
                        (click)="onClick()">    
                    </i>  
                    {{ course }}
                </span>
            </a>     
        </li>
    </ul>`
    providers: [CourseService]
})
export class CoursesComponent {

    title = "The title of courses page";
    courses;   

    constructor(courseService: CourseService){
        this.courses = courseService.getCourses();
    } 

    isActive = true;

    onClick($event){
        event.stopPropagation();
        this.isFavorite = !this.isFavorite;
        console.log("Clicked", $event);     
    }    
}

1 个答案:

答案 0 :(得分:1)

所有行都绑定到同一个isFavorite字段。不会为*ngFor中的每个项生成组件中的字段。只有一个。

要解决,请将其设为

<强>阵列

    <li *ngFor="#course of courses; let index=index">
        <a (click)="onClick()">
            <span>
              <i class="glyphicon"
                [class.glyphicon-star-empty]="!isFavorite[index]"
                [class.glyphicon-star]="isFavorite[index]"
                (click)="onClick(index)">    
              </i>
export class CoursesComponent {

    title = "The title of courses page";
    courses;  
    isFavorite; 

    constructor(courseService: CourseService){
        this.courses = courseService.getCourses();
        this.isFavorite = new Array(this.courses.length);
    } 

    isActive = true;

    onClick(index){
        event.stopPropagation();
        this.isFavorite[index] = !this.isFavorite;
    }    
}

或者 的对象

<i class="glyphicon"
    [class.glyphicon-star-empty]="!isFavorite[course]"
    [class.glyphicon-star]="isFavorite[course]"
    (click)="onClick(course)">    
</i>  
export class CoursesComponent {

    title = "The title of courses page";
    courses;  
    isFavorite = {}; 

    constructor(courseService: CourseService){
        this.courses = courseService.getCourses();
    } 

    isActive = true;

    onClick(course){
        event.stopPropagation();
        this.isFavorite[course] = !this.isFavorite;
    }    
}