简体   繁体   English

Angular2 QueryList基于元素类

[英]Angular2 QueryList based on element class

Is there a way to retrieve ViewChildren or ContentChildren by element class? 有没有办法按元素类检索ViewChildrenContentChildren

This will work, either by id or component but not for the class based queries, namely classedViewItems and classedContentItems 这可以通过id或组件工作,但不适用于基于类的查询,即classedViewItemsclassedContentItems

@Component({
    selector: 'my-container',
    template '<div><ng-content><ng-content></div>'
})
export class MyContainer {
    @ViewChildren('item') viewItems: QueryList;
    @ContentChildren(MyItem) contentItems: QueryList;
    @ViewChildren('.fine-me') classedViewItems: QueryList; // <-- need this to work
    @ContentChildren('.find-me') classedContentItems: QueryList; // <-- or this
}

for the following: 对于以下内容:

<my-container>
    <my-item class="find-me" #item *ngFor="let item; of items"></my-item>
</my-container>

I need to get the query list by the element class without decorating it. 我需要通过元素类获取查询列表而不进行装饰。

@ViewChild() , @ViewChildren() , @ContentChild() , @ContentChildren() only support the name of a template variable (or a comma separated list of names) or the types of components or directives as selectors as it is also mentioned in angular documentation. @ViewChild()@ViewChildren()@ContentChild()@ContentChildren()仅支持模板变量的名称(或逗号分隔的名称列表)或组件或指令的类型作为选择器,因为它也被提到在角度文档中。

There is no way to use other selectors. 没有办法使用其他选择器。 What you can do is to filter QueryList afterwards to only get the elements with a specific class but that doesn't free you from adding a template variable to each of them. 您可以做的是之后过滤QueryList以仅获取具有特定类的元素,但这不会使您无法向每个元素添加模板变量。

See also How can I select an element in a component template? 另请参见如何在组件模板中选择元素?

It's an old question, but thanks to this link about carousel by Netanet Basal are a work around about the question. 这是一个老问题,但是由于Netanet Basal关于旋转木马的这个链接是一个关于这个问题的工作。

If we write a simple directive, that has as selector a className -in the eg class "myClass", -you can add in the same .ts that your component, but don't forget declare in your module- 如果我们编写一个简单的指令,它具有className作为选择器 - 例如类“myClass”,你可以添加与你的组件相同的.ts,但不要忘记在你的模块中声明 -

@Directive({
  selector: '.myClass'
})
export class MyClassElement {
}

Make possible has some like 有可能有一些喜欢

@ViewChildren(MyClassElement , { read: ElementRef }) 
              private itemsElements : QueryList<ElementRef>;

In an .html 在.html中

<div class="myClass">one</div>
<div class="myClass">two</div>
<div class="myClass">three</div>

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

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