【问题标题】:Display button only if ng-content isnt empty仅当 ng-content 不为空时显示按钮
【发布时间】:2022-11-18 22:02:33
【问题描述】:

我读了很多书,老实说还没有看到任何有意义的解决方案。 所以我有一个组件,其中包含一个按钮和一个下拉列表来显示一些内容(在这种情况下是另一个按钮)。

烤肉串按钮组件:

<button>some button displaying dropdown<button>

<app-dropdown-component>
<ul>
<ng-content></ng-content>
</ul>
</app-dropdown-component>

看起来像这样。作为 ng-content,我在不同的组件中提供了一个列表项。 问题是我想在没有提供列表项时隐藏此按钮。 尝试在项目上使用 #ref 然后

@ViewChild('ref') items: ElementRef;

然后签入 ngAfterViewInit

this.showButton = this.items.nativeElement && this.items.nativeElement.children.length > 0

还有 .detectChanges();

但它通常说“无法读取未定义的属性‘nativeElement’”。 当 ng-content 没有提供任何元素时,有什么简单的方法可以隐藏我的按钮吗? 另外我不能在我的按钮上使用 *ngIf 所以寻找不同的方式。 我也可以接受从儿童角度的解决方案:

<app-kebab-button-component>
<li *ngIf="something">Something</li>
</app-kebab-button-component>

因此,仅当由于 *ngIf 语句而提供任何 &lt;li&gt; 时,我才会显示 kebab-button-component。

【问题讨论】:

    标签: angular typescript ng-content angular-content-projection


    【解决方案1】:

    你可以用 CSS 来处理这个问题:

    app-dropdown-component{
      display: flex;
      flex-direction: column-reverse;
    }
    
    app-dropdown-component ul:empty ~ button {
      display: none;
    }
    
    

    将带有display: flexflex-direction的项目和按钮的顺序颠倒为row-reversecolumn-reverse

    <app-dropdown-component>
      <ul>
        <ng-content></ng-content>
      </ul>
    
      <button>some button displaying dropdown<button>
    </app-dropdown-component>
    

    【讨论】:

      【解决方案2】:

      你必须命名你的 ng-content 组件:

      &lt;ng-content #ref&gt;&lt;/ng-content&gt;

      否则 ViewChild 不知道它在寻找什么。

      就个人而言,我尽可能避免使用 ViewChild。而是将 *ngIf 附加到内容绑定到的数据:

      <button *ngIf="items.length > 0">
      
      <div *ngFor="let item of items">{{item}}</div>

      希望有所帮助。

      【讨论】:

      • 哦是的,当然我实际上一直在我的 <ul> 上使用 #ref 标签,而不是在 <ng-content> 上忘记提到这一点,但无论如何我得到“无法读取未定义的属性(读取'nativeElement')而我尝试在 ngAfterViewInit 中控制台记录它。
      猜你喜欢
      • 2019-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多