Angular:用跨度包裹具有特定类的锚点,并在锚点旁边添加 svg,同时对两个元素进行样式设置

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

我想知道如何使用带有 span 元素的类 X 自动包装所有锚元素。 然后,将 svg 与锚点一起添加到跨度中。

插图

想象一下我有任意数量的锚元素声明如下:

<a class="x">text</a>

然后在执行一些给定的实现之后,我希望这是结果:

<span>
<svg xmlns="http://www.w3.org/2000/svg">
<!-- SVG content here -->
</svg>
<a class="x">text</a>
</span>

所有这一切同时保留了对所有 3 个元素进行样式设置的能力。

限制

我无法使用:

  • A
    selector:'a'
    ,因为我正在使用 Angular Material MatAnchor 组件,该组件已经在使用此选择器。

我不想:

  • 用自定义元素/组件替换锚元素。
  • 使用属性选择器。

之前的尝试

我尝试创建一个指令,动态创建一个组件来包装锚点:

import {Directive, OnInit, ViewContainerRef} from '@angular/core';
import {AnchorComponent} from "../components/typography/anchor/anchor.component";

@Directive({
  selector: 'a.x'
})
export class AnchorDirective implements OnInit {
  constructor(
    private viewContainer: ViewContainerRef,
  ) {

  }

  ngOnInit(): void {
    const nativeElement = this.viewContainer.element.nativeElement as HTMLAnchorElement;
    let anchorComponentComponentRef = this.viewContainer.createComponent(AnchorComponent,
      {
        projectableNodes: [[nativeElement]]
      });
  }
}

该组件具有以下模板:

<span>
<svg xmlns="http://www.w3.org/2000/svg">
<!-- SVG content here -->
</svg>
<ng-content></ng-content>
</span>

该组件具有以下样式:

span > * {
  outline: 1px solid red;
  background-color: rgba(255, 255, 255, 0.4)
}

上面的“作品”是指我能够用跨度包裹锚点并添加 svg。但是,样式仅应用于 svg,而不应用于锚点。

javascript html css angular wrapper
1个回答
0
投票

由于

ViewEncapsulation
的角度,您无法看到仅应用于
<ng-content/>
中的内容的 CSS,因此我们有两个选项来解决此问题:

  1. 您可以使用
    ::ng-deep
    来尝试设置内容的样式。

CSS

::ng-deep span > * {
  outline: 1px solid red;
  background-color: rgba(255, 255, 255, 0.4)
}
  1. 将此样式设置为
    global-styles.scss
    ,这样我们就不需要
    ng-deep
    ,因为无论如何它已被弃用!

代码

span > * {
  outline: 1px solid red;
  background-color: rgba(255, 255, 255, 0.4)
}

注意:我有点担心这个CSS是如何构造的,这段代码会将样式应用于跨度内的所有元素,所以它看起来有点危险,所以请只向跨度添加一个唯一的类以确保其他内容不受影响。

推荐的CSS

span.ultra-unique-name > * {
  outline: 1px solid red;
  background-color: rgba(255, 255, 255, 0.4)
}
© www.soinside.com 2019 - 2024. All rights reserved.