1

在 Angular 应用程序中,我有一个带有<ng-content></ng-content>. 我为将放入 ng-content 的内容添加了 scss 规则,但它们被忽略了。我试图解决 using :host,但它不起作用。

https://stackblitz.com/edit/angular-ewqhzj

包装器组件:

<app-embed>
   <p>Hello world!</p><h1 class="toBeColored">toBeColored</h1>
</app-embed>

嵌入组件中的样式:

:host {
  border: 5px solid red;
 padding: 15px;
 display: block;
 .toBeColored {
   color: pink;
 }
}

问题是未设置“toBeColored”字符串的粉红色

4

4 回答 4

2

尝试这个

:host ::ng-deep{
  border: 5px solid red;
  padding: 15px;
  display: block;
   .toBeColored {
    color: pink !important;
  }
}

并删除封装语句并尝试 ti build

encapsulation: ViewEncapsulation.Native
于 2019-11-11T12:16:39.000 回答
1

尝试添加封装: ViewEncapsulation.Native 到您的嵌入组件,如

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

@Component({
  selector: 'app-embed',
  templateUrl: './embed.component.html',
  styleUrls: ['./embed.component.scss'],
  encapsulation: ViewEncapsulation.Native
})
export class EmbedComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}
于 2019-11-11T12:35:50.747 回答
1

您无法以干净的方式实现这一目标。

一种解决方法是创建全局 css :

:host {
 ...;
 ::ng-deep .toBeColored {
   color: pink;
 }
}

但它会被弃用。看到这个问题

::ng-deep 将保存长期弃用 API 的网络记录。

于 2019-11-11T12:15:42.610 回答
1

您应该能够在将内容投影到 ng-content 标签的父组件中应用样式。角度样式隔离似乎将内容视为声明 HTML 的组件的一部分。

https://stackblitz.com/edit/angular-ivy-q9dn68

于 2021-05-17T03:49:33.900 回答