Ram_T
Ram_T

Reputation: 8484

References not working on component selector?

<my-selector #myRef class="element"></my-selector>

and in TS

@ViewChild('myRef') myRef: ElementRef;

accessing #myRef in its parent component like this.myRef is not giving DOM and it is giving the class and its property members.

We can style even it is not HTML element but Why can't we get it as DOM element rather component class?

Why references are not working on component selector?

Upvotes: 1

Views: 668

Answers (1)

Martin Parenteau
Martin Parenteau

Reputation: 73731

As mentioned in Angular documentation:

A template reference variable is often a reference to a DOM element within a template. It can also be a reference to an Angular component or directive or a web component.

In the following case, the template variable myRef refers to the component instance:

<my-selector #myRef class="element"></my-selector>
@ViewChild("myRef") myComponent: MyComponent;

If you make the component HTML element available as a public property:

@Component({
    selector: "my-selector",
    ...
})
export class MyComponent {

    constructor(private elementRef: ElementRef) { }

    public get domElement(): HTMLElement {
        return this.elementRef.nativeElement;
    }

    public doSomething() {
        ...
    }
}

you will have access to it as well as to other public members of the component:

export class ParentComponent {

    @ViewChild("myRef") myComponent: MyComponent;

    private someMethod() {
        let myComponentId = this.myComponent.domElement.id;
        ...
        this.myComponent.doSomething();
        ...
    }
}

Upvotes: 3

Related Questions