Angular 中多个组件的相同样式

问题描述 投票:0回答:2

我有多个(大约 6 个)组件(HTML)具有相同的样式,例如

<headertag>Some Content</headertag> <headertag>Some subtitle</headertag> Here there might be different content or svg/img or input fields. <button>accept</button> <button>cancel</button>

如何为这种情况添加通用样式。

例如:每个样式表都会有。

h2 { margin-top: 0; margin-bottom: 30px; color: Blue; }  button { display: flex; flex-direction: column; }

如何从每个样式表中删除重复的样式。我们使用的是scss。 有什么建议请 谢谢

我正在考虑 mixin,但觉得这不是一个好的选择。

html css angular sass scss-mixins
2个回答
0
投票

您可以使用“基本样式表” -> 如果样式在多个组件中非常常见,您可以创建一个包含这些常见样式的基本样式表。然后,将此基本样式表导入到您的组件样式表中。

// this is in file: _base.scss
h2 {
  margin-top: 0;
  margin-bottom: 30px;
  color: blue;
}
button {
  display: flex;
  flex-direction: column;
}

在您想要使用基本样式 SCSS 的组件中:

@import 'base';

希望这是您正在寻找的。祝你有美好的一天


0
投票

您可以使用

host
选择器的
@Component
属性,为所有组件添加一个公共类,然后在全局样式中添加。

全局样式.css

.common-changes h2 {
  margin-top: 0;
  margin-bottom: 30px;
  color: Blue;
}
.common-changes button {
  margin-top: 0;
  margin-bottom: 30px;
  color: Blue;
}

子组件 - 多个组件之一

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-a',
  template: `
  <h2 >Some Content</h2 > 
  <h2 >Some subtitle</h2 > 
  Here there might be different content or svg/img or input fields. 
  <button>accept</button> 
  <button>cancel</button>
  `,
  host: {
    class: 'common-changes',
  },
  standalone: true,
})
export class AComponent implements OnInit {
  constructor() {}

  ngOnInit() {}
}

堆栈闪电战

© www.soinside.com 2019 - 2024. All rights reserved.