在图片中,我点击后所有课程都被选中,但我只想选择一门课程(带星级)
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);
}
}
答案 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;
}
}