admin管理员组

文章数量:1401241

I have a ponent called abc and in that ponent I have three variable named title,Desc,Name and when I am trying to access it from nested function it gives me as undefined.

e.g.

@Component({
  selector: 'abc',
  templateUrl: './abcponent.html',
  styleUrls: ['./abcponent.css'],
  providers: [abcService]
})

export class abcComponent implements AfterViewInit,AfterViewChecked {

  title;
  Desc;
  Name;
  date=null;

test(){
this.title='a';
//work fine
}

test11(){

$('#cmg tbody').on('click', 'a.editor_edit', function (e) {
e.preventDefault();
this.title= false;  //gives me an undefined
});

}

}

I have a ponent called abc and in that ponent I have three variable named title,Desc,Name and when I am trying to access it from nested function it gives me as undefined.

e.g.

@Component({
  selector: 'abc',
  templateUrl: './abc.ponent.html',
  styleUrls: ['./abc.ponent.css'],
  providers: [abcService]
})

export class abcComponent implements AfterViewInit,AfterViewChecked {

  title;
  Desc;
  Name;
  date=null;

test(){
this.title='a';
//work fine
}

test11(){

$('#cmg tbody').on('click', 'a.editor_edit', function (e) {
e.preventDefault();
this.title= false;  //gives me an undefined
});

}

}
Share Improve this question edited Apr 30, 2018 at 10:09 Ankit Satapara asked Apr 30, 2018 at 9:45 Ankit SataparaAnkit Satapara 431 silver badge6 bronze badges 2
  • Just saying, mixing Angular with jQuery is not the best practice. – treecon Commented Apr 30, 2018 at 9:49
  • this is just because angular 5 not provided a data grid which I want. – Ankit Satapara Commented Apr 30, 2018 at 9:59
Add a ment  | 

1 Answer 1

Reset to default 10

This is because you are losing the scope in your callback. Modify it to use an arrow function so that you keep this

$('#cmg tbody').on('click', 'a.editor_edit', (e) => {
  e.preventDefault();
  this.title= false;
});

Until arrow functions, every new function defined its own this value (a new object in the case of a constructor, undefined in strict mode function calls, the base object if the function is called as an "object method", etc.). This proved to be less than ideal with an object-oriented style of programming.

本文标签: javascriptCannot Access this from nested function in angular4Stack Overflow