3

In this article Create Advanced Component the author selects an element by first creating a directive:

@Directive({
  selector: '.tooltip-container'
})
export class TooltipContainerDirective {}

And then using that directive to select the element containing the class .tooltip-container like this:

    @Component({
    template: `
        <div class="tooltip-container" [ngStyle]="{top: top}">
        <ng-content></ng-content>
        </div>
    `,
    styles: [...]
    })
    export class TooltipComponent implements OnInit {
    top : string;
    @ViewChild(TooltipContainerDirective, { read: ElementRef }) private tooltipContainer;


    }

Does Angular have the ability to select the tooltipContainer element by class name without using the directive?

Ole
  • 41,793
  • 59
  • 191
  • 359

1 Answers1

10

Hi I think your code should work,...
btw. you can use the ViewChild-Selector like a CSS-Selector (so @ViewChild('.tooltip-container') should work as well (notice: @ViewChild will only return the first result).
Furthermore you can use #myId on any HTML-Element and then select the child by using @VievChild('myId')

But I do not think that is your problem, is it possible your are trying to access the ViewChild in ngOnInit?, because that won't work... the child will be available as the view is rendered therefore the first time you can access the child is ngAfterViewInit.

Nickolaus
  • 4,785
  • 4
  • 38
  • 60
  • AHA! Yes good hunch. The tutorial author is accessing the `tooltipContainer` in `ngOnInit`, which is probably why he's using the `tooltip-container` directive to grab the `tooltipContainer ElementRef`. – Ole Jun 11 '19 at 19:11
  • 1
    Created a `
    ` inside a component, then added the view child ` @ViewChild('.test') testRef;` but i recieve the value as undefined
    – Ignacio Ambía Feb 17 '22 at 18:50
  • @ViewChild is not working directly with css selectors like classes and ids. But you can get around it via directives or you can just use plain JS `querySelector`s if you do not want to overcomplicate things. – Eugene P. Mar 25 '22 at 11:52