【问题标题】:Programmatically check if an Angular ng-content slot has been provided以编程方式检查是否提供了 Angular ng-content 插槽
【发布时间】:2020-11-23 21:07:09
【问题描述】:

我创建了一个使用内容投影和插槽的可扩展 Angular 组件,如下所示:

    <div class="content-wrapper">
      <div class="short-wrapper" [style.opacity]="expanded ? 0 : 1">
        <ng-content select="[short]"></ng-content>
      </div>

      <div class="full-wrapper" [style.opacity]="expanded ? 1 : 0">
        <ng-content select="[full]"></ng-content>
      </div>
    </div>

...在为组件的收缩(短)和扩展(完整)形式显示的内容之间进行选择。

每个组件也都有一个图标。我要做的是检测是否指定了[short] 内容,如果没有,则使用图标的放大版本作为组件的收缩状态内容。

但是,我不知道如何在我的组件的 Typescript 代码中 检测 [short] 内容是否存在。如果缺少 [short] 内容,我想以编程方式更改图标的 CSS 类,使其从左上角的小图标变为较大的居​​中图标,填充原本会消失的短内容空间。

【问题讨论】:

    标签: angular typescript components


    【解决方案1】:

    我不确定这是否是最好的方法,但这个解决方案有效:

    首先,我将名称#short 添加到以下div

          <div class="short-wrapper" #short [style.opacity]="expanded ? 0 : 1">
            <ng-content select="[short]"></ng-content>
          </div>
    

    然后我将其定义为ViewChild

     @ViewChild('short', { static: true }) shortRef: ElementRef;
    

    最后,在我的组件的ngOnInit()方法中,我可以测试shortdiv的内容是否为空,如果没有指定short插槽,则为空。

      ngOnInit(): void {
        if ((this.shortRef.nativeElement.innerHTML ?? '').trim() === '')
          this.useIconForShortContent = true;
      }
    

    【讨论】:

      猜你喜欢
      • 2020-08-24
      • 1970-01-01
      • 1970-01-01
      • 2011-06-18
      • 2014-09-06
      • 2016-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多