check if an HtmlElement has a directive


I would like to know how to check if an Element implements some directive.
I have two directives, a Sortable and a SortableItem, once the onDrop within SortableItem fires, I will call some binded function on the Sortable parent.
The problem is that the target of the drop event is some element within the SortableItem element, thus, I need to find the original SortableItem that is being used as dropzone.
I am doing it by looping through the parents of the and checking if the Element has the attribute selector of the SortableItem, however, I have the feeling that this is no the correct way to do this.


If you know the type of the directives you can use @ViewChild(), @ViewChildren(), @ContentChild(), or @contentChildren() to query for elements with that directive

@ViewChildren(Sortable) QueryList<Sortable> sortables;
@ViewChildren(SortableItem) QueryList<SortableItem> sortableItems;

When the directives contain

class Sortable {
  final ElementRef elementRef;

you can search the QueryList to find the matching element.

someEvent(Element sortable) {
  var found = sortables.toArray().firstWhere((s) => s.elementRef == sortable, orElse: () => null);
} contains a sortable list. It might provide some hints how to do this in Angular2.

Answered By – Günter Zöchbauer

Answer Checked By – Clifford M. (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *