我点击angular2
中的图标后尝试添加多个类这是我的代码:
import {Component, ElementRef, Renderer} from 'angular2/core';
import {CourseService} from './courses.service';
import {AutoGrowDirective} from './auto-grow.directive';
@Component({
selector: 'courses',
template: `<i (click)="onclick($event)" class="glyphicon glyphicon-star"></i>
<h3>Courses</h3>
{{title}}
<input type="text" autoGrow/>
<ul>
<li *ngFor="#course of courses">
{{course}}
</li>
</ul>`,
providers: [CourseService],
directives: [AutoGrowDirective]
})
export class CoursesComponent {
title:string = "List of course";
courses;
constructor(courseService:CourseService, private el:ElementRef, private renderer:Renderer) {
this.courses = courseService.getCourses();
}
onclick($event) {
this.renderer.setElementClass(this.el.nativeElement, 'glyphicon glyphicon-star-empty', true);
}
}
但是当我点击图标时,我的浏览器控制台会抛出此错误:
EXCEPTION: Error during evaluation of "click"
我认为这是因为类之间的空格,我自己无法想象的是如何在元素中添加多个类?
答案 0 :(得分:5)
只需为每个班级分别致电this.renderer.setElementClass(...)
,然后将isAdd
参数设为true
this.renderer.setElementClass(this.el.nativeElement, 'glyphicon', isAdd: true);
this.renderer.setElementClass(this.el.nativeElement, 'glyphicon-star-empty', isAdd: true);
(未经测试)
<强>更新强>
@Component({
selector: 'courses',
template: `<i (click)="onclick($event)" class="glyphicon glyphicon-star"></i>
<h3>Courses</h3>
{{title}}
<input type="text" autoGrow/>
<ul>
<li *ngFor="#course of courses">
{{course}}
</li>
</ul>`,
providers: [CourseService],
directives: [AutoGrowDirective]
})
export class CoursesComponent {
title:string = "List of course";
courses;
constructor(courseService:CourseService) {
this.courses = courseService.getCourses();
}
@HostBinding('class.glyphicon')
@HostBinding('class.glyphicon-star-empty')
_isGlyphIcon:boolean = false;
onclick($event) {
this._isGlyphIcon = true;
}
}
<强> UPDATE2 强>
@Component({
selector: 'courses',
template: `<i (click)="onclick($event)" [ngClass]="_iconClasses"></i>
<h3>Courses</h3>
{{title}}
<input type="text" autoGrow/>
<ul>
<li *ngFor="#course of courses">
{{course}}
</li>
</ul>`,
providers: [CourseService],
directives: [AutoGrowDirective]
})
export class CoursesComponent {
title:string = "List of course";
courses;
constructor(courseService:CourseService) {
this.courses = courseService.getCourses();
}
_iconClasses:string[] = ['glyphicon', 'glyphicon-star'];
onclick($event) {
this._iconClasses = ['glyphicon', 'glyphicon-star-empty'];
}
}