Angular 2.x在body标签上绑定类

时间:2015-12-23 07:26:24

标签: javascript angular

由于Angular 2.x是在体内引导的,我如何在body标签上添加[class.fixed]="isFixed"(在my-app之外)?

<html>
<head>
</head>
<body [class.fixed]="isFixed">
  <my-app>Loading...</my-app>
</body>
</html>

我的app组件看起来像

import {Component} from 'angular2/core';
import {CORE_DIRECTIVES} from 'angular2/common';
import {RouteConfig, ROUTER_DIRECTIVES, Router, Location} from 'angular2/router';
import {About} from './components/about/about';
import {Test} from './components/test/test';

@Component({
    selector: 'my-app',
    providers: [],
    templateUrl: '/views/my-app.html',
    directives: [ROUTER_DIRECTIVES, CORE_DIRECTIVES],
    pipes: []
})

@RouteConfig([
    {path: '/about', name: 'About', component: About, useAsDefault: true},
    {path: '/test', name: 'Test', component: Test}
])

export class MyApp {
    router: Router;
    location: Location;

    constructor(router: Router, location: Location) {
        this.router = router;
        this.location = location;
    }
}

1 个答案:

答案 0 :(得分:21)

使用<body>作为app组件工作正常,但你不能在<body>标签上使用绑定,因为它试图将“isFixed”绑定到父级,并且没有父级。

使用@HostBinding代替

@Component(
  selector: 'body',
  templateUrl: 'app_element.html'
)
class AppElement {
  @HostBinding('class.fixed') 
  bool isFixed = true;
}

这是Dart代码,但将其转换为TS应该不难。

另见@HostBinding and @HostListener: what do they do and what are they for?

如果您不依赖于服务器端呈现或Web工作者,则可以始终使用纯JS来更新DOM。

或者你也可以使用

document.body.classList.add('foo');