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

Yuv*_*als 3 javascript angular

我有一个嵌套组件SearchBar作为我的标题的子.我的组件定义:

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

search-form.component.html正在使用以下指令:

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

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

.ng2-tag-input-field {
    padding: 5px;
    border-radius: 6px;
    margin-right: 10px;
    direction: ltr;
    text-align: right;
}
Run Code Online (Sandbox Code Playgroud)

除非我把CSS放在Styles.css文件中,否则CSS规则对嵌套指令没有影响.为什么这不能按预期工作?

Sur*_*yan 9

您需要更改组件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
})
Run Code Online (Sandbox Code Playgroud)

Angular 2内置了视图封装,使我们能够使用Shadow DOM.有三种视图封装类型:

1)ViewEncapsulation.None - 根本没有Shadow DOM.因此,也没有样式封装.

2)ViewEncapsulation.Emulated - 没有Shadow DOM但是样式封装模拟.

3)ViewEncapsulation.Native - Native Shadow DOM,它的优点.

有关更多信息,请参阅角度2中的视图封装

  • 如果我使用 ViewEncapsulation.None 它会破坏我导入的(嵌套)类。我想影响瀑布(嵌套组件),但不受主机组件外部的影响。 (2认同)