2016-12-19 47 views
1

如果用户登录或者不登录,我需要改变class的值,我在app.component.ts和login.component.ts这里检查了它们;用ngClass设置body元素的class属性值

app.component.ts

export class AppComponent { 
    isAuthenticated:boolean; 
    constructor(private auth:Auth){ 
     this.isAuthenticated=this.auth.authenticated(); 
    } 
} 

login.component.ts

export class LoginComponent { 
    isAuthenticated:boolean; 
    constructor(private auth:Auth){ 
    this.isAuthenticated=this.auth.authenticated(); 
    } 
} 

和index.html

<body [ngClass]="{ 
    'dashboard site-navbar-small' :isAuthenticated, 
    'login-form login-form-second page-login-second' :!isAuthenticated 
}"> 
    <app-root>Loading...</app-root> 

但它不工作 在这里,我怎么看起来浏览器; enter image description here

+0

你能告诉我它不起作用吗? –

+0

我觉得最后一次编辑更清楚了,什么都行不通。我期望一个类的值设置为属性,但你看到它的原始字符串typecrpt代码 – TyForHelpDude

+0

你如何解决它? –

回答

0

角应用程序的根组件是body标签内:Angular 2 documentation所以我们不能body标签直接

而对于现在的角度有只给标题服务获取/设置的标题绑定页面

export class AppComponent { 
    title = 'app works!'; 
    public constructor(private titleService:Title){ 
    this.titleService.setTitle('My ToDo'); 
    } 

对于body标签,您可以使用setElementClass plunker或者您可以使用jQuery

setElementClass(document.body, "dashboard site-navbar-small", isAuthenticated) 
setElementClass(document.body, "login-form login-form-second page-login-second", !isAuthenticated) 
+0

这是有道理的,但仍无法解决,无法使用此,renderer一些如何仍然在它 – TyForHelpDude

0

您是否尝试将构造函数的逻辑转化为简单函数?它应该如何工作?你能提供关于代码中逻辑的更多信息吗?

app.component.ts

export class AppComponent { 
    isAuthenticated:boolean = false; 

    private toggle(){ 
    this.isAuthenticated = !this.isAuthenticated; 
    } 
} 

login.component.ts

export class LoginComponent { 
    isAuthenticated:boolean = false; 

    private toggle2(){ 
    this.isAuthenticated = !this.isAuthenticated; 
    } 
} 

index.html

<body [ngClass]="{ 
    'dashboard site-navbar-small': isAuthenticated, 
    'login-form login-form-second page-login-second': !isAuthenticated 
}"> 
</body> 

编辑

您正试图将函数绑定到布尔变量。你确定它看起来像这样吗? this.isAuthenticated = this.auth.authenticated();

+0

它返回true或false ofc我相信 – TyForHelpDude