他们是如何在 Clarity 中删除 Angular 组件包装元素的

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

我注意到 Clarity 设计系统的按钮在 DOM 中不包含包装元素。我喜欢这个有多种原因(清晰 - 无双关语,可访问性)。

我四处寻找解决方案来完成这样的事情。一些解决方案可能会影响 Angular 变更检测和其他机制。

Clarity 选择的解决方案看起来非常干净。但我无法让它工作:我设法得到的最佳结果仍然是获得包装元素和作为同级元素放置在 DOM 中的内容。

这是 Clarity 按钮的代码: https://github.com/vmware-clarity/ng-clarity/blob/main/projects/angular/src/button/button-group/button.ts 这就是它的渲染方式: enter image description here

据我所知他们是如何做到的:

  • 将组件内容放入带有 ref 的 ng-template 中
  • 将引用链接到子视图
@Component({
  selector: 'clr-button',
  template: `
    <ng-template #buttonProjectedRef>
      <button
export class ClrButton implements LoadingListener {
  @Output('click') _click = new EventEmitter<boolean>(false);

  @ViewChild('buttonProjectedRef', { static: true }) templateRef: TemplateRef<ClrButton>;

奇怪的是,我看不到 viewchild 的属性名称(“templateRef”)在哪里使用。

angular
1个回答
0
投票

实际上按钮组件有自己的选择器

clr-button
,但这本身不起作用,它需要一个父组件
clr-button-group

在演示中,这就是他们的使用方式

  <clr-button-group>
    <clr-button>1</clr-button>
    <clr-button>2</clr-button>
    <clr-button>3</clr-button>
    <clr-button [clrInMenu]="true">4</clr-button>
    <clr-button [clrInMenu]="true">5</clr-button>
    <clr-button [clrInMenu]="true">6</clr-button>
  </clr-button-group>

所以按钮存在于

Content Children

内部

因此按钮组首先采用所有按钮的内容子项

按钮组 Ts

export class ClrButtonGroup implements AfterContentInit, AfterViewInit {
  @Input('clrToggleButtonAriaLabel') clrToggleButtonAriaLabel: string = this.commonStrings.keys.rowActions;

  @ViewChild('menuToggle') menuToggle: ElementRef<HTMLElement>;
  @ViewChild('menu') menu: ElementRef<HTMLElement>;

  @ContentChildren(ClrButton) buttons: QueryList<ClrButton>; // this line here!

处理完成后,按钮被推至

menuButtons
,最后对按钮进行循环并使用
ng-template

进行渲染

按钮组 HTML

<ng-template *ngFor="let menuButton of menuButtons" [ngTemplateOutlet]="menuButton.templateRef"></ng-template>
© www.soinside.com 2019 - 2024. All rights reserved.