Reputation: 389
Is there a way to send through HTML the element as an attribute? For example:
In HTML:
<ul>
<li *ngFor="let item of items">
<my-component [ngClass]="{'whatever': checkElement(my-component)}">
</li>
</ul>
In ts file:
checkElement(el): boolean {
// dummy code
const size = el.getBoundingClientRect();
return size.bottom > 100;
}
I know there are several ways to get that element, but this will be used in a huge loop and I would like to prevent searching the element in the DOM (if possible).
Thanks!
Upvotes: 2
Views: 2178
Reputation: 156
You can you a template reference variable to refer to my-component
like so:
<my-component [ngClass]="{'whatever': checkElement(myComponentVariableName)}" #myComponentVariableName>
and pass that as an argument to the method checkElement()
. Note that here the type of myComponentVariableName
will be HTMLInputElement
.
Another way to access that from the .ts
file would be to use @ViewChild()
like so:
@ViewChild('myComponentVariableName') myComponentVariable: ElementRef;`.
Then you can use this.myComponentVariable
anywhere inside the component.
If you are worried about having multiple my-component
s as it is inside an *ngFor
, you can convert the @ViewChild
statement to make it a list like so:
@ViewChildren(my-component) myComponentList: QueryList<my-component>;
Also, track the *ngFor
by index, and send the index along with the template reference variable like so:
<li *ngFor="let item of items; let i=index;">
<my-component [ngClass]="{'whatever': checkElement(myComponentVariableName, i)}" #myComponentVariableName>
</li>
Inside the checkElement()
method, access the particular my-component
like myComponentList[i]
.
Upvotes: 2
Reputation:
Sure, very easy :
export class ParentComponent {
this = this;
}
<my-element [parentElement]="this">
now in your second component
@Input('parentElement') parentElement: ParentComponent;
Upvotes: 0