Angular2 Components :: ViewChild / ContentChild by class
<p>I am trying to design an expandable component like so:</p>

<pre><code>&lt;collapsable [expanded]="myFlag"&gt;
  &lt;div title&gt;Summary&lt;/div&gt;
  &lt;div alternate-title&gt;Heading&lt;/div&gt;
  &lt;div content&gt;Details&lt;/div&gt;
&lt;/collapsable&gt;
</code></pre>

<p>The <code>alternate-title</code> portion is supposed to be optional. When <code>myFlag = false</code>, the component should render only:</p>

<pre><code>&lt;div title&gt;Summary&lt;/div&gt;
</code></pre>

<p>However, when <code>myFlag = true</code>, the component should render one of the following:</p>

<pre><code>// If alternate-title exists..
&lt;div alternate-title&gt;Heading&lt;/div&gt;
&lt;div content&gt;Details&lt;/div&gt;

// If alternate-title does not exist..
&lt;div title&gt;Summary&lt;/div&gt;
&lt;div content&gt;Details&lt;/div&gt;
</code></pre>

<p>Right now, I have the template for this component defined as follows:</p>

<pre><code>&lt;ng-content *ngIf="!expanded" select="[title]"&gt;&lt;/ng-content&gt;
&lt;ng-content *ngIf="expanded"  select="[alternate-title]"&gt;&lt;/ng-content&gt;
&lt;ng-content *ngIf="expanded"  select="[content]"&gt;&lt;/ng-content&gt;
</code></pre>

<p>This works fine for the first scenario (if <code>alternate-title</code> exists). However, in the second scenario, it doesn't work (obviously). To get it to work for the second scenario, I need to get a reference to <code>alternate-title</code> in my component. One way to do that is below:</p>

<pre><code>// In page.html..
&lt;div #alternateTitle alternate-title&gt;...&lt;/div&gt;

// In component.ts
@ContentChild('alternateTitle') alternateTitle: ElementRef;
</code></pre>

<p>However, I don't like this approach as it forces me to define a local variable for <code>alternate-title</code> which is redundant. </p>

<p>Is there a way I can get a reference to <code>alternate-title</code> in my component to check whether or not the user of my component defined it or not?</p>