For example in my-components-list.html I have:
<my-component #first></my-component>
<my-component #second></my-component>
<my-component #third></my-component>
<input #forth/>
And I want to get it in my test like:
it('test', () => {
const myComponent: HTMLElement = fixture.debugElement.query(By.someMethod('#first'));
const myInput: HTMLElement = fixture.debugElement.query(By.someMethod('#forth'));
}
To get started using template reference variables, simply create a new Angular component or visit an existing one. To create a template reference variable, locate the HTML element that you want to reference and then tag it like so: #myVarName .
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 (Read more at Angular.io). That means you can easily access the variable anywhere in the template.
A template reference variable is a feature that allows us to gain access to a part of our template. This could be an element, component, or could be a directive.
You can use the template reference variables like you would use them in normal Angular code. Define them with the @ViewChild decorator as fields in your component class:
@ViewChild('first') first: ElementRef;
@ViewChild('second') second: ElementRef;
...
Then in your test you can access them like normal component fields: fixture.componentInstance.first
I first expected a dynamic solution for this problem where i can access the elements by reference variable name but the more i think about the described solution i think it is the correct way. It is more typesafe and the elements are encapsulated as part of the component and not the template.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With