Reputation: 1991
I have a few divs in an array that I want to change the height on, and even though when I log the names of the divs and it gives me the right object names, I still get a "this is undefined" error message in the console.
Like I said, when I log out all the names of the divs they are correctly given through, but on the line where I want to set their height, I guess that there is a problem with "this" somewhere.
this.divs.forEach(names);
function names(div) {
console.log(div); //goes thought all the divs correctly
this._renderer.setElementStyle(div.nativeElement, 'height', largestHeight + 'px');
}
I am doing it in angular2 in case someone was wondering. Regards for any help.
Upvotes: 1
Views: 58
Reputation: 1499
There is no this
in your function context, try to use arrow function:
this.divs.forEach((names) => {
...
});
You can also bind this
to your function.
this.divs.forEach(names.bind(this));
Upvotes: 2
Reputation: 24581
Problem is here
function names(div) {
In JavaScript this is belonging to the current function unless you pass another this
:
this.divs.forEach(names.bind(this));
or in ES6
let names = (div) => {
console.log(div); //goes thought all the divs correctly
this._renderer.setElementStyle(div.nativeElement, 'height', largestHeight + 'px');
}
Upvotes: 1