In Angular, you can create a template reference variable on a component using the same syntax as for DOM elements or directives. You just need to add the '#' symbol followed by a name to the component selector in your template.
Here's an example:
<app-my-component #myComponentRef></app-my-component>
<button (click)="logComponent(myComponentRef)">Log Component</button>
In this example, we're creating a template reference variable called 'myComponentRef' for an instance of the 'app-my-component' component. We're also binding to the click event of a button and passing the reference to the component instance to a function called 'logComponent'.
In our component class, we can define the 'logComponent' function like this:
logComponent(componentRef: MyComponent) {
console.log(componentRef);
}
When we click the button, the 'logComponent' function will be called with the reference to the 'app-my-component' component instance.
Note that in order to use the template reference variable with a component, you need to define the component class in your component's module and import it into your component's module or the app module.
Also, the type of the template reference variable is the component class, not the component selector. So, in our example, the type of 'myComponentRef' is 'MyComponent'.
Comments
Post a Comment