Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using @ViewChild to select an element by Class name? [duplicate]

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?

like image 588
Ole Avatar asked Oct 20 '25 03:10

Ole


1 Answers

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.

like image 119
Nickolaus Avatar answered Oct 21 '25 17:10

Nickolaus