英文:
Default content for ng-content when using ngIf
问题
I have this Angular 9 component, named inner:
<div #ref>
<ng-content select="[content]"></ng-content>
</div>
<ng-container *ngIf="!ref.hasChildNodes()">
<div>Default value</div>
</ng-container>
It will be displayed "Some content" if I use it in a parent component this way:
<inner><div content>Some content</div><inner>
It will be displayed "Default value" if I use it in a parent component this way:
<inner><inner>
But in this case:
<inner><div content *ngIf="false">Some content</div><inner>
nothing is displayed. "Some content" is not displayed because the condition is false, but also "Default value" is not displayed.
How can I show "Default value" in this case?
我有一个名为 inner 的 Angular 9 组件:
<div #ref>
<ng-content select="[content]"></ng-content>
</div>
<ng-container *ngIf="!ref.hasChildNodes()">
<div>Default value</div>
</ng-container>
如果我在父组件中这样使用它:
<inner><div content>Some content</div><inner>
它将显示 "Some content"。
如果我在父组件中这样使用它:
<inner><inner>
它将显示 "Default value"。
但在这种情况下:
<inner><div content *ngIf="false">Some content</div><inner>
什么都不显示。"Some content" 不显示是因为条件为 false,但 "Default value" 也不显示。
在这种情况下,如何显示 "Default value"?
英文:
I have this Angular 9 component, named inner:
<div #ref>
<ng-content select="[content]"></ng-content>
</div>
<ng-container *ngIf="!ref.hasChildNodes()">
<div>Default value</div>
</ng-container>
It will be displayed "Some content" if I use it in a parent component this way:
<inner><div content>Some content</div><inner>
It will be displayed "Default value" if I use it in a parent component this way:
<inner><inner>
But in this case:
<inner><div content *ngIf="false">Some content</div><inner>
nothing is displayed. "Some content" is not displayed because condition is false, but also "Default value" is not displayed.
How can I show "Default value" in this case?
I could use a class instead of attribute in the select. But I always prefer use classes to be used by CSS, not for this kind of logic.
答案1
得分: 1
你可以使用 HTMLDivElement
的另一个属性来使其工作,就像这样:
<div #ref>
<ng-content select="[content]"></ng-content>
</div>
<ng-container *ngIf="!ref.childElementCount">
<div>默认值</div>
</ng-container>
英文:
You can use another prop from HTMLDivElement
and get things work, like this:
<div #ref>
<ng-content select="[content]"></ng-content>
</div>
<ng-container *ngIf="!ref.childElementCount">
<div>Default value</div>
</ng-container>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论