ContentChildren类选择器

Aym*_*man 9 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 {
}
Run Code Online (Sandbox Code Playgroud)

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

Som*_* S. 8

您可以通过创建指令来完成此操作.让我们Class用选择器调用它[class],字符串输入绑定到'class',并且输入变量上的hostbinding也绑定到'class'.

然后对您感兴趣的特定类进行@ContentChildren(Class, {descendants: true, read: ElementRef})过滤QueryList.

这是有片段:

另见Plunker在这里工作

// 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]    

  }
}
Run Code Online (Sandbox Code Playgroud)

  • 注意:这是角度材质 `matTabContent` 指令使用的机制 https://github.com/angular/components/blob/master/src/material/tabs/tab-content.ts https://material.angular.io /组件/选项卡/概述 (2认同)

waw*_*wka 6

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

@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 {
}
Run Code Online (Sandbox Code Playgroud)

  • 您不应在一个模板中声明 #grouped 两次。模板引用变量在一个模板内应该是唯一的。`引用变量的范围是整个模板。因此,不要在同一模板中多次定义相同的变量名称,因为运行时值将是不可预测的。` https://angular.io/guide/template-syntax#ref-vars (3认同)
  • 这里有太多的上下文使用“分组”一词。 (2认同)
  • 这不是按类查询,而是使用#grouped`查询 (2认同)