@ContentChildrenデコレータを使用してソリューションを実装しました。これは、@ Lernerの回答に似ています。
ドキュメントによると、このデコレータは次のとおりです。
コンテンツDOMから要素またはディレクティブのQueryListを取得します。子要素が追加、削除、または移動されるたびに、クエリリストが更新され、クエリリストで監視可能な変更により新しい値が出力されます。
したがって、親コンポーネントに必要なコードは次のようになります。
<app-my-component>
<div #myComponentContent>
This is my component content
</div>
</app-my-component>
コンポーネントクラスの場合:
@ContentChildren('myComponentContent') content: QueryList<ElementRef>;
次に、コンポーネントテンプレートで:
<div class="container">
<ng-content></ng-content>
<span *ngIf="*ngIf="!content.length""><em>Display this if ng-content is empty!</em></span>
</div>
完全な例: https //stackblitz.com/edit/angular-jjjdqb
私は、このソリューションが角度コンポーネントに実装されていることを発見しましmatSuffixた。フォームフィールドコンポーネントの。
成分の含有量が、後に注入された状況で、後にアプリが初期化され、我々はまたに加入することで、反応性の実装を使用することができるchangesのイベントQueryList:
export class MyComponentComponent implements AfterContentInit, OnDestroy {
private _subscription: Subscription;
public hasContent: boolean;
@ContentChildren('myComponentContent') content: QueryList<ElementRef>;
constructor() {}
ngAfterContentInit(): void {
this.hasContent = (this.content.length > 0);
this._subscription = this.content.changes.subscribe(() => {
this.hasContent = (this.content.length > 0);
});
}
ngOnDestroy() {
this._subscription.unsubscribe();
}
}
完全な例:https://stackblitz.com/edit/angular-essvnq