【问题标题】:Why there's an array of strings instead of only one string in angular2 styles?为什么在 angular2 样式中有一个字符串数组而不是一个字符串?
【发布时间】:2016-10-20 09:24:06
【问题描述】:

我正在尝试学习Angular2,但是我对组件样式有点困惑,在组件装饰器中我们可以指定将它们应用到我们的组件的样式,有两种方法可以做到这一点:

1- 我们可以在 styleUrls 属性中指定 css 文件,它是一个字符串数组,这对我来说是逻辑,因为我们可能有多个 css 文件

@Component({
    selector: 'users-list',
    templateUrl: 'app/users-list.template.html',
    styleUrls: ['style1.css', 'style2.css']
})

2- 我们可以在 styles 属性中编写我们的样式,它也是一个字符串数组,这就是我感到困惑的地方!我的意思是为什么样式属性是一个字符串数组?为什么它不仅仅是一个字符串!

@Component({
    selector: 'users-list',
    templateUrl: 'app/users-list.template.html',
    styles: [
        `
            .glyphicon{
                cursor: pointer;
            }
        `
    ]
})

在 Angular2 的官方文档中,他们没有说明为什么要在其中放置一个字符串数组而不是一个字符串!谁能解释一下!!

【问题讨论】:

  • 实际上他们将其视为一个 json 字符串,并从中选择类,然后将行为应用到该类

标签: css angular


【解决方案1】:

styles 数组中提供的所有 CSS 字符串将组合应用于组件。乍一看,这可能听起来毫无用处,但如果您想混合多种并非全部硬编码到组件的样式,它就会派上用场。例如:

import commonStyles from "./commonStyles";

@Component({
    selector: 'users-list',
    templateUrl: 'app/users-list.template.html',
    styles: [
        ".glyphicon { cursor: pointer; }",
        commonStyles.background // This string of style rules gets applied too!
    ]
})

编辑:回答 cmets 中的问题:

commonStyles 在这种情况下只是一个包含 CSS 字符串的普通 JavaScript 对象:

export default {
    background: "div { background-color: #00FF00; }"
};

以这种方式做事的一个好处是你的应用程序不必发出额外的 HTTP 请求来获取 styleUrls(也就是说,我对 Angular 2 还不够熟悉,无法说明这是否会使明显的差异)。

【讨论】:

  • 你能解释一下 commonStyles 里面有什么吗?它是一个普通的样式表文件吗?
  • stylescommonStyles.backgroundstyleUrls 一起使用有什么区别或优势?
【解决方案2】:

例如,您可以使用共享样式文件

@Component({
    selector: 'users-list',
    templateUrl: 'app/users-list.template.html',
    styleUrls: ['users-list.css', 'common-theme.css']
})

【讨论】:

  • 好吧,我问的是样式属性而不是 styleUrls。
【解决方案3】:

所以如果数组项超过两个,他们可以通过特殊的迭代来获取文件。

这就是他们编程的方式,而不是使用'style1.css style2.css'

如果他们使用字符串。他们将添加一项功能。

  1. 分开刺。输出数组
  2. 迭代数组以获取文件。

他们使用数组来缩短流程并使应用程序更快。如果你正在使用 angular2 构建一个小应用程序。它不会伤害你。但是,如果您正在处理数百万个数据。它也可以提供帮助,但不会太多。至少。

问候。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多