简体   繁体   English

Angular2 Components :: ViewChild / ContentChild

[英]Angular2 Components :: ViewChild / ContentChild by class

I am trying to design an expandable component like so: 我正在尝试设计一个可扩展的组件,如下所示:

<collapsable [expanded]="myFlag">
  <div title>Summary</div>
  <div alternate-title>Heading</div>
  <div content>Details</div>
</collapsable>

The alternate-title portion is supposed to be optional. alternate-title部分应该是可选的。 When myFlag = false , the component should render only: myFlag = false ,组件应仅渲染:

<div title>Summary</div>

However, when myFlag = true , the component should render one of the following: 但是,当myFlag = true ,组件应呈现以下之一:

// If alternate-title exists..
<div alternate-title>Heading</div>
<div content>Details</div>

// If alternate-title does not exist..
<div title>Summary</div>
<div content>Details</div>

Right now, I have the template for this component defined as follows: 现在,我有这个组件的模板定义如下:

<ng-content *ngIf="!expanded" select="[title]"></ng-content>
<ng-content *ngIf="expanded"  select="[alternate-title]"></ng-content>
<ng-content *ngIf="expanded"  select="[content]"></ng-content>

This works fine for the first scenario (if alternate-title exists). 这适用于第一种情况(如果存在alternate-title )。 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 alternate-title in my component. 为了让它适用于第二个场景,我需要在我的组件中引用alternate-title One way to do that is below: 一种方法是在下面:

// In page.html..
<div #alternateTitle alternate-title>...</div>

// In component.ts
@ContentChild('alternateTitle') alternateTitle: ElementRef;

However, I don't like this approach as it forces me to define a local variable for alternate-title which is redundant. 但是,我不喜欢这种方法,因为它迫使我为alternate-title定义一个冗余的局部变量。

Is there a way I can get a reference to alternate-title in my component to check whether or not the user of my component defined it or not? 有没有办法可以在我的组件中获得对alternate-title的引用,以检查我的组件的用户是否定义了它?

We need a wrapper element with a template variable: 我们需要一个带有模板变量的包装元素:

<ng-content *ngIf="!expanded" select="[title]"></ng-content>
<span #titleWrapper><ng-content *ngIf="expanded"  select="[alternate-title]"></span></ng-content>
<ng-content *ngIf="expanded"  select="[content]"></ng-content>

Then we can query the element using @ViewChild() and then check if it contains the content we are interesed in: 然后我们可以使用@ViewChild()查询元素,然后检查它是否包含我们所介入的内容:

@ViewChild('titleWrapper') titleWrapper:ElementRef;

ngAfterContentInit() {
  let title = this.titleWrapper.nativeElement.querySelector('[alternative-title]');
  ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM