【发布时间】: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 语句而提供任何 <li> 时,我才会显示 kebab-button-component。
【问题讨论】:
标签: angular typescript ng-content angular-content-projection