在Angular2中对嵌套组件应用css规则

Apply css rules on nested component in Angular2

本文关键字:应用 css 规则 组件 嵌套 Angular2      更新时间:2023-09-26

我有一个嵌套组件SearchBar作为我的Header的子组件。我的组件定义:

@Component({
  moduleId: module.id,
  selector: 'search-form',
  templateUrl: 'search-form.component.html',
  styleUrls: [ 'search-form.component.css']
})

search-form.component.html在内部使用了以下指令:

<tag-input placeholder="Add tags ..." 
    [(model)]="tagsArray" 
    (tagsChanged)="onTagsChange($event)"
    (tagsAdded)="onTagsAdded($event)"
    (tagRemoved)="onTagRemoved($event)"
    [delimiterCode]="[32]"></tag-input>

search-form.component.html我有以下规则:

.ng2-tag-input-field {
    padding: 5px;
    border-radius: 6px;
    margin-right: 10px;
    direction: ltr;
    text-align: right;
}

CSS规则对嵌套指令没有影响,除非我把CSS放在Styles.css文件中。为什么它没有像预期的那样工作?

您需要更改组件的viewEncapsulation

import { ViewEncapsulation} from '@angular/core';
@Component({
  moduleId: module.id,
  selector: 'search-form',
  templateUrl: 'search-form.component.html',
  styleUrls: [ 'search-form.component.css'],
  encapsulation: ViewEncapsulation.None
})
Angular 2内置了视图封装,这使我们能够使用Shadow DOM。有三种视图封装类型:

1) ViewEncapsulation。无 -没有影子DOM。因此,也没有样式封装。

2) ViewEncapsulation。仿真 -没有影子DOM,但样式封装仿真。

3) ViewEncapsulation。原生 -原生阴影DOM的所有优点。

更多信息请参见VIEW ENCAPSULATION IN ANGULAR 2