【发布时间】:2017-04-06 20:23:41
【问题描述】:
如何在 AngularJS 2 中处理这样一种情况:单击一个元素时需要更改自己的样式,如果其他元素具有该样式,则需要将其删除——最好是在一个函数中。
类似于Angular.js How to change an elements css class on click and to remove all others,仅在 AngularJS 2 中,使用 TypeScript。
组件
https://plnkr.co/edit/Q2BoU4sNnXdaJB5vrZ8h?p=preview
//our root app component
import { NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import {Component} from '@angular/core';
@Component({
selector: 'my-app',
providers: [],
template: `
<div>
<div (click)="isClassVisible = !isClassVisible;" [ngClass]="{'my-class': isClassVisible }">
> I'm a div that gets styled on click
</div>
<div (click)="isClassVisible = !isClassVisible;" [ngClass]="{'my-class': isClassVisible }">
> I also want to be styled but only when Im clicked
</div>
<div (click)="isClassVisible = !isClassVisible;" [ngClass]="{'my-class': isClassVisible }">
> When one of us gets clicked the we want to be the only one with the style all others go back to normal
</div>
<div (click)="isClassVisible = !isClassVisible;" [ngClass]="{'my-class': isClassVisible }">
> I'm just here cause my creator likes even numbers
</div>
</div>
`,
styles: [
`
.my-class {
background-color: yellow;
}
`
]
})
class App {
isClassVisible: false;
constructor() {
}
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App ],
bootstrap: [ App ]
})
export class AppModule {}
【问题讨论】:
-
一些使用Harrys answer plnkr.co/edit/z9PoHsPsc3k2dKzUH7zi?p=info的附加功能
标签: javascript html css angular typescript