【问题标题】:Custom CSS attributes for Angular componentsAngular 组件的自定义 CSS 属性
【发布时间】:2018-06-16 17:17:02
【问题描述】:

我有一个封装图片轮播的 Angular 组件。 If 使用 :host 选择器使自己成为一个 flexbox 并使用 ngFor 为通过 @Input 属性传递给它的图片数组中的每张图片重复一个 img 标签。

我有两个相关的问题。

1) 我想让图片的样式设置为固定的高度或宽度。 2)我想在imgs上设置margin-right和margin-bottom以允许间隔图片。

棘手的部分是我希望在主机模板中确定这些设置,而不是轮播模板,以便它们可以根据特定页面的需要而变化。

我已经使用这样的自定义 css 属性让它工作了:

图像列表 css:

:host {
    display: flex;
    flex-flow: row wrap;
    justify-content: flex-start;
    align-items: flex-start;
}

img {
    height: var(--pictureMaxHeight,-1);    
    margin-right: var(--pictureSpacing,0);
    margin-bottom: var(--pictureSpacing,0);
}

调用模板css:

image-list {
   --pictureMaxHeight: 300px;
   --pictureSpacing: 0.5em;
   justify-content: center;
}

我收到以下警告:

自定义属性被忽略:不限于顶级 :root 元素 (image-list { ... --pictureMaxHeight: ... })

全文:

警告 ./src/app/pages/image-list-test/image-list-test.component.css(发射 值而不是错误的实例)postcss-custom-properties: /home/username/wwwroot/src/app/pages/image-list-test/image-list-test.component.css:2:5: 自定义属性被忽略:不限于顶级 :root 元素 (图像列表 { ... --pictureMaxHeight: ... }) NonErrorEmittedError: (发出的值而不是错误的实例) postcss-自定义属性: /home/username/wwwroot/src/app/pages/image-list-test/image-list-test.component.css:2:5: 自定义属性被忽略:不限于顶级 :root 元素 (图像列表 { ... --pictureMaxHeight: ... }) 在 Object.emitWarning (/home/username/wwwroot/node_modules/webpack/lib/NormalModule.js:117:16) 在 result.warnings.forEach (/home/username/wwwroot/node_modules/postcss-loader/lib/index.js:149:49) 在 Array.forEach (本机) 在 postcss.process.then (/home/username/wwwroot/node_modules/postcss-loader/lib/index.js:149:27) @ ./src/app/pages/image-list-test/image-list-test.component.ts 48:21-62@./src/app/app.module.ts@./src/main.ts@multi webpack-dev-server/client?http://0.0.0.0:0./src/main.ts

我尝试在 app.component.css 文件中声明变量,但对收到的错误没有影响。

此外,为项目中的每个组件声明自定义属性会完全破坏封装。

有趣的是它可以工作,即使有警告。

我知道我可以声明一个自定义的 html 属性,但由于这与组件的结构无关,而且是纯粹的视觉样式,这对我来说似乎很臭。

我在这里遗漏了什么还是有更好的方法来解决这个要求?

【问题讨论】:

  • 如何使用 导入 template.css。至少这是我摆脱警告的方式

标签: angular css templates css-variables


【解决方案1】:

Angular(或您)正在使用 postcss-custom-properties 插件(如您在消息中所见)的自定义属性,这些属性需要您为每个属性声明 @custom-properties:root 选择器零件。您可以通过传递选项来disable the warning

如果可以的话,我建议你使用遵循 css 规范的 postcss-css-variables。所以,从你的 sn-p 开始,你可以拥有这个,这要好得多并且解耦:

:host {
  --pictureMaxHeight: var(--public-var);
  --pictureSpacing: var(--public-var);

  display: flex;
  flex-flow: row wrap;
  justify-content: flex-start;
  align-items: flex-start;
}

img {
  height: var(--pictureMaxHeight,-1);    
  margin-right: var(--pictureSpacing,0);
  margin-bottom: var(--pictureSpacing,0);
}

【讨论】:

  • 我尝试了您的解决方案,它产生了相同的警告。我还尝试在 :root 而不是 :host 中将自定义变量分配添加到 var(--public-var) ,但这也不起作用。
  • 关闭警告是可行的,虽然这很麻烦,因为它需要弹出 ng-cli webpack 配置。
  • 我的 sn-p 仅在您使用 postcss-css-variables 而不是 postcss-custom-properties(返回警告的那个)时才起作用
猜你喜欢
  • 2019-04-12
  • 1970-01-01
  • 1970-01-01
  • 2020-02-27
  • 2018-01-05
  • 2019-04-21
  • 2018-09-08
  • 2018-04-23
  • 2011-01-12
相关资源
最近更新 更多