typescript Angular2 - 将 CSS 类添加到所选元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40115436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular2 - Adding CSS class to selected element
提问by FacundoGFlores
I have the following code in my .html
:
我的代码中有以下代码.html
:
<ul id="navbar-example" class="nav nav-pills nav-stacked" *ngFor="let object of objects; let i = index;">
<li class="nav-item" *ngIf = "i==0">
<a id="{{object.code}}" class="nav-link active" (click)="clicked(object)">{{object.name}}</a>
</li>
<li class="nav-item" *ngIf = "i!=0">
<a id="{{object.code}}" class="nav-link" (click)="clicked(object)">{{object.name}}</a>
</li>
</ul>
So the first element is active when the ul
is loaded. Now I want to add the active
class to the selected <a></a>
and toggle that which has active
. How can I achieve it?
所以第一个元素在ul
加载时处于活动状态。现在我想将active
类添加到选定的类<a></a>
并切换具有active
. 我怎样才能实现它?
EDIT:
编辑:
I simplified to this:
我简化为:
<ul id="navbar-example" class="nav nav-pills nav-stacked" *ngFor="let object of objects;">
<li class="nav-item" >
<a [ngClass]="{ 'active': selected == object }"(click)="clicked(object)">{{object.names}}</a>
</li>
</ul>
but it does not work. This is my component:
但它不起作用。这是我的组件:
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { objectsService } from './objects.service';
import { object } from './object';
@Component({
selector: 'objects',
styles: [require('./object.css')],
template: require('./objects.html'),
})
export class objects implements OnInit {
objects: object[];
codvisita: string;
selected: any;
constructor(private route: ActivatedRoute, private objectsService: objectsService) {
}
ngOnInit() {
this.route.params.forEach((params: Params) => {
this.codvisita = params['id'];
});
this.objectsService.getobjects(this.codvisita)
.subscribe(
objects => {
this.objects = objects;
this.selected = this.objects[0];
console.log(this.selected);
}
);
}
clicked(e) {
this.selected = e;
console.log(this.selected);
}
}
回答by Stefan Svrkota
Create a variable in your component, let's call it temp
and then set value of temp
to selected object in your click event:
在您的组件中创建一个变量,让我们调用它temp
,然后temp
在单击事件中将值设置为所选对象:
temp: any;
clicked(object) {
this.temp = object;
}
And then in your template you can use NgClass
directive to achieve what you want:
然后在您的模板中,您可以使用NgClass
指令来实现您想要的:
<ul id="navbar-example" class="nav nav-pills nav-stacked" *ngFor="let object of objects; let i = index;">
<li class="nav-item">
<a id="{{object.code}}" class="nav-link" [ngClass]="{ 'active': temp.code == object.code }" (click)="clicked(object)">{{object.name}}</a>
</li>
</ul>