[英]Angular2 - two way databinding on a component variable / component class property?
[英]How to access or update the component class variable in other component class angular2
我有正文,對於主頁,我想將“ home”類和“ other”類應用於其余頁面。 該主體在index.html中定義。
現在,appcomponent為Index.html提供了公共變量“ homePage = true”。 對於其他頁面,我想訪問此變量並設置“ homePage = false”。
如果您使用的是Angular RC4,則可以在應用程序組件中執行以下操作以檢查URL並設置homePage
變量:
import { Router, NavigationEnd } from '@angular/router';
import { Component, OnInit } from '@angular/core';
@Component({
selector : 'app'
})
export class AppComponent implements OnInit {
public homePage: Boolean = true;
private router: Router;
constructor(router: Router){
this.router = router;
}
ngOnInit() {
this.router.events.subscribe((events) => {
if (events instanceof NavigationEnd) {
if (events.url === '/' || events.url === '/home') {
this.homePage = true;
} else {
this.homePage = false;
}
}
});
this.homePage = (this.router.url === '/' || this.router.url === '/home') ? true : false;
}
}
另外,您還必須將body標簽更改為: <body [ngClass] = "{'home':homePage, 'other':!homePage}">
我認為您需要擺脫class =“ home” ...
<body [ngClass]="{home: homePage, other: !homePage}">
雖然,我不確定您如何在body標簽上使用angular 2指令。您應該在主體內部有一個標簽,該標簽是主要組成部分(即,您用角度引導的標簽),因此該標簽之外的任何內容都不會可以用angular 2的真棒醬增強。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.