Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a reference to all elements projected in Component?

Tags:

angular

What should I do if I want to get a reference to all elements projected in my Component?

Let's say I have AppComponent which projects some links and images into TestComponent:

@Component({
  selector: 'test',
  template: '<ng-content></ng-content>'
})
class TestComponent {}

@Component({
  selector: 'app',
  template: `
    <test>
      <img src="http://example.org/1.jpg">
      <a href="http://example.org">Some Link</a>
    </test>
  `,
  directives: [ TestComponent ]
})
export class AppComponent {}

Now how can I get a reference to those links and images (and potentially other element types) inside my TestComponent ?

Reading this post suggests the following:

Solution: ContentChildren + directive with li selector

One great solution is to take advantage of the selector in the @Directive decorator. You simply define a directive that selects for <li> elements, then use a @ContentChildren query to filter all <li> elements down to only those that are content children of the component.

But this only works if I want to get a single element type, but if I want to get more than one type that means I have to create a directive for each type I want (and what if I want all types?)...this doesn't feel like a practical method.

Is there another way? or is direct DOM manipulation the only solution in this case?

like image 491
Amr Noman Avatar asked Feb 06 '23 16:02

Amr Noman


1 Answers

You can try using multiple selectors on the directive like this:

@Directive({ selector: 'a, img' })

Angular only allows directives to trigger on CSS selectors that do not cross element boundaries. So selector may be declared as one of the following:

  • element-name: select by element name.
  • .class: select by class name.
  • [attribute]: select by attribute name.
  • [attribute=value]: select by attribute name and value.
  • :not(sub_selector): select only if the element does not match the sub_selector.
  • selector1, selector2: select if either selector1 or selector2 matches.
like image 133
yurzui Avatar answered Feb 13 '23 06:02

yurzui