我如何处理 AngularJS 2 中的一种情况,即单击一个元素需要更改其自己的样式,并且如果其他元素具有该样式,则需要将其删除 - 最好在一个函数中。
如同Angular.js 如何在单击时更改元素 css 类并删除所有其他元素 https://stackoverflow.com/questions/17928487/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 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 {}
解决问题的最简单方法是为每个包含的元素分配一个唯一的 ID,并使用另一个变量来保存选定的 ID。开启逻辑my-class
CSS 类现在将基于所选的 ID。
您的新 HTML 模板:
<div (click)="toggleHighlight(1);" [ngClass]="{'my-class': highlightedDiv === 1}">
> I'm a div that gets styled on click
</div>
Your toggleHighlight
功能:
highlightedDiv: number;
toggleHighlight(newValue: number) {
if (this.highlightedDiv === newValue) {
this.highlightedDiv = 0;
}
else {
this.highlightedDiv = newValue;
}
}
工作粉克:https://plnkr.co/edit/fNoXWhUhMaUoeMihbGYd?p=preview https://plnkr.co/edit/fNoXWhUhMaUoeMihbGYd?p=preview
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)