मैंने @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, में पाया है फॉर्म-फील्ड घटक में।
स्थिति जब घटक की सामग्री पर बाद में इंजेक्ट किया जाता है में, के बाद एप्लिकेशन initialised है, हम भी एक प्रतिक्रियाशील कार्यान्वयन का उपयोग कर सकते हैं, करने के लिए सदस्यता लेने के द्वारा 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