【问题标题】:Angular2 Dynamically add styles to styleUrls arrayAngular2动态添加样式到styleUrls数组
【发布时间】:2017-10-02 19:24:33
【问题描述】:

我正在用 Agular2 编写一个应用程序,我们的一些组件允许父级添加样式类。像这样:
子组件。

@Component({
selector: 'app-label-value',
templateUrl: './label-value.component.html',
styleUrls: ['./label-value.component.css']
})
export class LabelValueComponent implements OnInit {

@Input() label: string;
@Input() value: string;
@Input() valueClass: string;
@Input() labelClass: string;
@Input() cssFile: string;

getLabelClasses(){
  let classList = 'label-value-label '
  if (this.labelClass){
    classList += this.labelClass;
  }
  return classList;
}

子模板:

<div [ngClass]="getLabelClasses()">
  {{label}}
</div>

在父模板内。

<app-label-value 
  [label]="'Just text'" 
  [value]="'some text'"
  [labelClass]="'label-color standard-text'"
  [cssFile]="'./app.component.css'">
</app-label-value>

这不起作用。 div 获取 label-value-label label-color standard-text 类,但它们不是从 ./app.component.css 类文件中加载的(因此不显示)。
子组件需要以某种方式找到./app.component.css 路径并将其添加到styleUrls 数组。或者告诉组件在哪里寻找类文件的其他方法。但我似乎不知道该怎么做(或者即使有可能)。

【问题讨论】:

  • 可能是课程不收费。您可以尝试:>>> 在 css 文件中的类前面吗?
  • 如果你把label-value-label label-color standard-tex放到styles.css文件中,是否有效?
  • 显然,将 label-value-label label-color 标准文本放入 ./label-value.component.css 是可行的。但我想让父母给孩子自己(或任何其他)css文件。

标签: html css angular


【解决方案1】:

在 Angular4 中,从父级到子级甚至子级到父级共享样式表尚不可行 您将可以访问您在组件样式表中提到的唯一样式。

但是您可以选择为一个组件包含多个样式表。在组件中,您可以有一个样式表列表。

@Component({
    selector: 'app-component',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css', './someother.css', './another.css']
})

如果你想为整个项目提供一个样式,你可以在 style.css 中编写它,它是全局编译的,而不是特定于组件的。

【讨论】:

    【解决方案2】:

    我的问题是ViewEncapsulation。
    一旦我在父组件上设置了encapsulation: ViewEncapsulation.None,它的 CSS 文件就对所有其他组件可见,包括我的子组件。所以我不需要手动将 CSS 文件包含在我的子组件的 styleUrls 数组中,浏览器会发现它。
    当然,最好的解决方案是将所有“全局”样式放在应用根目录的 style.css 文件中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-21
      • 2017-07-07
      • 2012-02-03
      • 2016-07-13
      • 2018-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多