我刚刚在ngx GitHub repo上在线浏览Angular 4.0组件,基本上只是标题组件,如下所示:
<div class="header-container"
[class.left]="position === 'normal'"
[class.right]="position === 'inverse'">
<div class="logo-containter">
<a (click)="toggleSidebar()" href="#" class="navigation"><i class="nb-menu"></i></a>
<div class="logo" (click)="goToHome()">ngx-<span>admin</span></div>
</div>
<ngx-theme-switcher></ngx-theme-switcher>
</div>
问题是我无法理解class
代码的工作方式,我看到下面的代码并且我无法理解它:
[class.left]="position === 'normal'"
[class.right]="position === 'inverse'"
上面的代码到底是做什么的?
标题组件的typescript文件如下所示:
import { Component, Input, OnInit } from '@angular/core';
import { NbMenuService, NbSidebarService } from '@nebular/theme';
import { UserService } from '../../../@core/data/users.service';
import { AnalyticsService } from '../../../@core/utils/analytics.service';
@Component({
selector: 'ngx-header',
styleUrls: ['./header.component.scss'],
templateUrl: './header.component.html',
})
export class HeaderComponent implements OnInit {
@Input() position = 'normal';
user: any;
userMenu = [{ title: 'Profile' }, { title: 'Log out' }];
constructor(private sidebarService: NbSidebarService,
private menuService: NbMenuService,
private userService: UserService,
private analyticsService: AnalyticsService) {
}
ngOnInit() {
this.userService.getUsers()
.subscribe((users: any) => this.user = users.nick);
}
toggleSidebar(): boolean {
this.sidebarService.toggle(true, 'menu-sidebar');
return false;
}
toggleSettings(): boolean {
this.sidebarService.toggle(false, 'settings-sidebar');
return false;
}
goToHome() {
this.menuService.navigateHome();
}
startSearch() {
this.analyticsService.trackEvent('startSearch');
}
}
答案 0 :(得分:4)
将条件css类应用于元素是一种简便的语法。
[class.left]="position === 'normal'"
如果left
评估为position === 'normal'
,则会将css类truthy
应用于该元素,否则将不会应用该类。
请参阅Template syntax documentation作为参考。
此处还有语法documentation from the cheat sheet
<div [class.extra-sparkle]="isDelightful">
将元素上存在的CSS类额外闪烁与表达式
的真实性联系起来isDelightful