1

I am initializing a library in my ngOnInit method as follows:

ngOnInit() {
this.$grid = jQuery('.grid').masonry({
  // options
  itemSelector: '.grid-item',//,
  columnWidth: 384,
  gutter: 24
});
......
}

then i am calling this method from that instance, inside ngOnInit as well:

 // bind event listener
this.$grid.on( 'layoutComplete',function onLayout() {
  console.log(this.$grid);     
} );

so it the method finally looks like this:

ngOnInit() {
this.$grid = jQuery('.grid').masonry({
  // options
  itemSelector: '.grid-item',//,
  columnWidth: 384,
  gutter: 24
});

 // bind event listener
this.$grid.on( 'layoutComplete',function onLayout() {
  console.log(this.$grid);     
} );

}

But I dont understand why the result printed by console.log is undefined if actually is this.$grid who is calling console.log.

I need to use that instance again inside that method to do something like this:

// bind event listener
this.$grid.on( 'layoutComplete',function onLayout() {
  this.$grid.masonry('layout');
} );

but I can not because this.$grid is undefined inside that method which does no makes sense for me at all.

Any ideas?

D.B
  • 4,009
  • 14
  • 46
  • 83

2 Answers2

1

This is because of the way you are binding your event.

In your code this refers to the execution context of the anonymous function you've passed to the on function (e.g. itself).

If you want to preserve the context of this, you have to use an arrow function like this:

this.$grid.on( 'layoutComplete', () => {
    this.$grid.masonry('layout');
});
ADreNaLiNe-DJ
  • 4,787
  • 3
  • 26
  • 35
0

try call these inside the AfterViewInit callback lifecycle.

ngAfterViewInit(): void {
  this.$grid = jQuery('.grid').masonry({
  itemSelector: '.grid-item',
  columnWidth: 384,
  gutter: 24
 });
 this.$grid.on( 'layoutComplete',() => {
  console.log(this.$grid);     
 });
}

ngAfterViewInit(): Respond after Angular initializes the component's views and child views. Called once after the first ngAfterContentChecked(). A component-only hook.

see angular documentation https://angular.io/guide/lifecycle-hooks

Anto Antony
  • 842
  • 6
  • 12
  • The lifecycle is not the problem. It's a problem of the "context" of `this`. Take a look to this question: https://stackoverflow.com/questions/41106125/angular-2-using-this-inside-settimeout – ADreNaLiNe-DJ Nov 14 '17 at 12:36
  • @ADreNaLiNe-DJ you are right. and i will correct my answer. – Anto Antony Nov 14 '17 at 12:45