如何访问或更新其他组件类angular2中的组件类变量

How to access or update the component class variable in other component class angular2

本文关键字:组件 angular2 类变量 其他 更新 何访问 访问      更新时间:2023-09-26

我有主体,对于主页,我想为页面的其余部分应用'home'类和'other'类。该主体在index.html中定义。

现在appcomponent为Index.html添加了公共变量'主页= true'。对于其他页面,我想访问这个变量并设置"主页= false"。

我认为你需要摆脱class="home"…

<body [ngClass]="{home: homePage, other: !homePage}">

虽然,我不确定如何在body标签上有angular 2指令。你应该在主体内部有一个标签,这是主要组件(即:你引导angular的那个),这样之外的任何东西都不会被angular 2的强大功能增强。

在你的应用组件中,如果你使用的是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}">