ContentChildren类选择器

时间:2017-05-01 20:59:20

标签: angular

我有像Angular这样的两个组件

@Component({
  selector: 'content-com',
  template: '<ng-content></ng-content>'
})
class ContentComponent {
    // Select all the elements with .grouped css class
    @ContentChildren('.grouped') grouped;
}

@Component({
  selector: 'main-com',
  template: `<content-com>
    <div class="grouped"></div>
    <div class="grouped"></div>
  </content-com>`
})
class MainComponent {
}

是否可以使用css选择器(在我的案例类选择器中)选择所有内容子项?如果没有,最好的办法是什么?

2 个答案:

答案 0 :(得分:8)

您可以通过创建指令来完成此操作。我们使用选择器Class将其称为[class],将字符串输入绑定到&#39; class&#39;输入变量上的hostbinding也绑定到'class'

然后执行@ContentChildren(Class, {descendants: true, read: ElementRef})并针对您感兴趣的特定课程过滤QueryList

这是有片段:

  

另见Plunker working here

// Remember to declare this in Module 
@Directive({selector: '[class]'})
class Class  { 
  @HostBinding('class') @Input('class') className: string = '';    
}

@Component({
  selector: 'content-com',
  template: '<ng-content></ng-content>'
})
class ContentComponent implements AfterContentInit {
  // Select all the elements with .grouped css class
  @ContentChildren(Class, {descendants: true, read: ElementRef}) classes: QueryList<ElementRef>; // <--- Note This change 

  get grouped() {
    if ( this.classes && this.classes.length ) {
      return this
        .classes
        .map((elRef:ElementRef):Element => elRef.nativeElement)
        .filter( (element: Element) => element.className == "grouped" );
    }

    return [];
  }

  ngAfterContentInit(){

      console.log( this.grouped ); // <-- expect (2) [div.grouped, div.grouped]    

  }
}

答案 1 :(得分:4)

您可以轻松完成,无需创建指令。你必须知道的是ContentChildren的选择器必须是变量名。所以:

&#13;
&#13;
@Component({
  selector: 'content-com',
  template: '<ng-content></ng-content>'
})
class ContentComponent {
    @ContentChildren('grouped') grouped: QueryList<ElementRef>;
}

@Component({
  selector: 'main-com',
  template: `<content-com>
    <div class="grouped" #grouped></div>
    <div class="grouped" #grouped></div>
  </content-com>`
})
class MainComponent {
}
&#13;
&#13;
&#13;