首页 > 解决方案 > Angular - 如何在 ng-content 中设置类的样式?

问题描述

我有这个文件上传组件<ng-content>。当用户将文件从操作系统悬停到文件上传区域时,组件内的所有标签都继承background-color: rgba(121, 211, 255, 0.15);自该类。.fileover但我无法让背景颜色更改.ag-center-cols-viewport<ng-content>. 我曾尝试使用::slotted::ng-deep。最后的图片显示,background-color: red;如果我更改 chrome devtols 内的颜色,它会起作用。

::ng-深度文档

::slotted 文档

有什么建议为什么这不起作用?

HTML:

 <div>
            <div class="containerDragDrop" appDnd (fileDropped)="onFileDropped($event)">
              <input class="inputDragDrop file-input" type="file" #fileupload accept="{{accept}}"
                     [disabled]="disabled" multiple
                     (change)="addFiles($event)"/>
                     <ng-content class="fileDropRef"></ng-content>
              <div class="middleFileText">
      </div>
      <label *ngIf="choseFileToggle" class="labelDragDrop" (click)="fileupload.click()">Välj Filer</label>
            </div>
          </div>

带 ::slotted 的 CSS:

.fileover {
  .middleFileText{
    opacity: 0.8;
  }
  background-color: rgba(121, 211, 255, 0.15);
  :host ::slotted(.ag-center-cols-viewport) {
    background-color: rgba(121, 211, 255, 0.15) !important;
  }
}

带有 ::ng-deep 的 CSS:

.fileover {
  .middleFileText{
    opacity: 0.8;
  }
  background-color: rgba(121, 211, 255, 0.15);
  :host ::ng-deep .ag-center-cols-viewport {
    background-color: rgba(121, 211, 255, 0.15) !important;
  }
}

在此处输入图像描述

在此处输入图像描述

标签: htmlcssangular

解决方案


我缺少一些有关您的 html 代码所在位置以及 ag-center-cols-viewport 是什么的信息,但我认为您确实将其添加到组件中。让我们说my.component.htmlag-center col 被导入到你的@NgModule

注意: ::ng-deep弃用,将在 Angular 的未来版本中删除,请不要再使用它

my.component.ts 添加以下内容

@Component({
  selector: 'my-component',
  templateUrl: './my.component.html',
  styleUrls: ['./my.component.scss'],
  encapsulation: ViewEncapsulation.None, // <-- Here, we remove the style encapsulation
})

然后my.component.scss像这样写

 my-component { // Name of your selector
  .fileover {
  .middleFileText{
    opacity: 0.8;
  }
  background-color: rgba(121, 211, 255, 0.15);
  .ag-center-cols-viewport {
    background-color: rgba(121, 211, 255, 0.15) !important;
  }
}
}

如果这不起作用,可能是因为您使用的组件确实在更高级别加载代码,这意味着代码不在您的组件内,而是在外部,添加到 DOM 中的某个位置。

为了能够使用 css 更改它,您必须将全局 css 添加到style.css位于文件夹根src目录的

.ag-center-cols-viewport {
    background-color: rgba(121, 211, 255, 0.15) !important;
}

如果您不希望 css 全局更改,那么您应该找到一种方法将一些自定义 css 类名称添加到ag-center-cols-viewport


推荐阅读