如何在每个子组件的父组件中设置元素类?

时间:2017-08-09 15:45:30

标签: angular

在app.component(应用程序的主要部分)中,我有:

<div id="wrapper">
<!-- Header
================================================== -->
    <header  class="transparent sticky-header full-width">
.
.
.
    <div class='container-fluid'>
        <div class='row'>
            <div class='col-sm-3'>
                <nav-menu></nav-menu>
            </div>
            <div class='col-sm-9 body-content'>
                <flash-messages></flash-messages>
                <ng2-toasty></ng2-toasty>
                <router-outlet></router-outlet>
            </div>
        </div>
    </div>
.
.
.

我希望标题仅在home.component上保持“透明”类。在所有其他组件上,我想保留其他两个类,而不是“透明”。

可以更好地解释组件结构的层次结构如下图所示:

enter image description here

因此,home组件不是父组件,但app.component是父组件。 home.component和其他人一样是孩子。

app.component.ts

import { Component, ErrorHandler } from '@angular/core';
import { ToastyService } from "ng2-toasty";
import { AppErrorHandler } from "../../app.error-handler";
import { HomeComponent } from "../home/home.component";
import { ActivatedRoute, Router } from "@angular/router";

@Component({
    selector: 'app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    providers: [
        HomeComponent,
        ToastyService,
        { provide: ErrorHandler, useClass: AppErrorHandler }
    ]
})
export class AppComponent {
    classes: string;
    constructor(private home: HomeComponent, private route: ActivatedRoute,
        private router: Router) {
        //this.classes = false;
        //if (this.router.url ==='/home')
        //{
        //    this.classes = true;
        //}
        this.classes = "transparent sticky- header full- width";
    }
}

我曾尝试制作变量类并使用ngClass传递它,但它不起作用。

我搜索了解决方案,我发现的所有解决方案都基于事件。

2 个答案:

答案 0 :(得分:1)

解决此问题的一种方法是在此图中添加另一个名为TestVC()的组件。

enter image description here

顶部图像听起来就像现在的样子。底部图像是另一种方法。

您可以改为删除标题以及您在app.component的每个页面上不想要的任何内容,并且只有Main Component

然后你可以添加一个router-link,其中包含你想要的每个页面上的所有内容。然后它将包含一个Main Component,它将托管需要标题的应用程序的每个其他页面。

可选地

您可以尝试使用ngClass。这允许您根据值指定CSS类。以下是我的一个例子:

router-outlet

如果<span [ngClass]="{'glyphicon glyphicon-exclamation-sign': !isValid('tags')}"> 方法返回false,则打开定义的样式类。

然后,您需要定义一些要绑定的属性,并确保在适当时设置属性。你可以用服务做到这一点。

答案 1 :(得分:0)

使用全局css文件而不是每个组件css可以解决您的问题。您可以使用ViewEncapsulation自定义此行为。