Angular 使用 FontAwesome:无法设置路径样式

Angular with FontAwesome: cannot style path

我创建了一个新项目,安装了 font-awesome:

"@fortawesome/angular-fontawesome": "^0.4.0",
"@fortawesome/fontawesome-svg-core": "^1.2.19",
"@fortawesome/free-brands-svg-icons": "^5.9.0",

导入FontAwesomeModule:

imports: [
    ...,
    FontAwesomeModule
],

并创建了一个简单的图标:

faFacebook = faFacebook;
<fa-icon [icon]="faFacebook"></fa-icon>

图标显示成功。现在我想为生成的图标设置 path 的样式:

path {
  fill: red;
}

但是没用。我的 Chrome 甚至没有在开发者工具中打印这条规则。

如何设计 path?我必须精确设置样式 path,而不是 fa-icon(以使用 fill: url(#gradient) 应用渐变)。

Angular 默认提供样式封装(仿真)。这意味着每个组件都是独立的,同一页面中的 2 个组件之间不会有任何冲突。 (例如,如果他们使用相同的 class 名称)。

https://angular.io/guide/component-styles

来自Angular官方文档:

View encapsulation

As discussed earlier, component CSS styles are encapsulated into the component's view and don't affect the rest of the application.

To control how this encapsulation happens on a per component basis, you can set the view encapsulation mode in the component metadata. Choose from the following modes:

  • ShadowDom view encapsulation uses the browser's native shadow DOM implementation (see Shadow DOM on the MDN site) to attach a shadow DOM to the component's host element, and then puts the component view inside that shadow DOM. The component's styles are included within the shadow DOM.

  • Native view encapsulation uses a now deprecated version of the browser's native shadow DOM implementation - learn about the changes.

  • Emulated view encapsulation (the default) emulates the behavior of shadow DOM by preprocessing (and renaming) the CSS code to effectively scope the CSS to the component's view. For details, see Appendix 1.

  • None means that Angular does no view encapsulation. Angular adds the CSS to the global styles. The scoping rules, isolations, and protections discussed earlier don't apply. This is essentially the same as pasting the component's styles into the HTML.

要为组件中包含的元素设置样式(如果组件库本身未提供此功能),那么您有 2 个选项:

1) 将您的样式添加到全局 styles.css

在全局 styles.css.

中定义的样式没有任何封装

在你的组件中:

<fa-icon class="my-global-icon" [icon]="faFacebook"></fa-icon>

在你的styles.cssstyles.scss中:

fa-icon.my-global-icon path {
  fill: red;
}

2) 禁用封装仿真

默认情况下,封装在组件内定义的样式上处于活动状态(模拟)。 要禁用它,您应该设置 encapsulation = ViewEncapsulation.None

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ],
  encapsulation: ViewEncapsulation.None
})
export class AppComponent  {
...

在这种情况下,您将能够为组件的直接子元素中包含的子元素设置样式。但要小心,您可能会遇到其他样式冲突问题。现在管理它们是你的工作了。

希望对您有所帮助。

你可以通过传递[style]属性直接更改fontawesome图标的样式,如下所示。

<fa-icon [icon]="faFacebook" [styles]="{'stroke': 'red', 'color': 'red'}">
</fa-icon>