Home > Enterprise >  Angular shadowed this pointer
Angular shadowed this pointer

Time:08-25

Upgrading Angular broke some of my code. Previously the following statement worked:

@Component({
  templateUrl: './some.component.html',
  styleUrls: ['./some.component.scss']
})
export class SomeComponent {
  ...
  public someMethod(): void {
    const defs = this.svg.select(function() {return this.parentNode; })
      .append('defs');
    ...
  }
  ...
}

Now this will throw the following two error messages:

'this' implicitly has type 'any' because it does not have a type annotation.
An outer value of 'this' is shadowed by this container.

What is the correct replacement for this line?

CodePudding user response:

You could try using an ES5 arrow function instead. Arrow functions don't clobber or override this.

  public someMethod(): void {
    const defs = this.svg.select(() => this.parentNode)
      .append('defs');
    ...
  }

If that doesn't fix it, use another variable to return from the function scope:

  public someMethod(): void {
    const myParentNode = this.parentNode;
    const defs = this.svg.select(() => myParentNode)
      .append('defs');
    ...
  }

CodePudding user response:

The solution to this particular problem was actually multifaceted:

  • Upgrading the used ES version
  • Upgrading D3js

The statment can be translated to:

this.svg.select(function(this:any) {return this.parentNode;})
  • Related