2

Angular2 and jQuery combo is confusing me. Please help! When I invoke a popup dialog, and onApprove case, I want to call Component's level function test(), however, it it causing a run time error:

"TypeError: this.test is not a function"

Any advice is appreciated!

import { Component, OnInit } from '@angular/core';
declare var $: any;

    enter code here

@Component({
  selector: 'app-schedule',
  templateUrl: './schedule.component.html',
  styleUrls: ['./schedule.component.less']
})

export class ScheduleComponent implements OnInit {

  scheduled : boolean;
  constructor() {
    this.scheduled = false;
   }

  ngOnInit() {
  }

  test() {
    console.log('hello');
  }

  deleteConfirmDlg() {
    $('.mini.modal')
      .modal({
        closable  : false,
        onDeny    : function(){
          window.alert('Wait not yet!');
          return false;
        },
        onApprove : function() {
          this.test();
        }
      }).modal('show');
  }
}

1 Answer 1

3

You should use right arrow operator to have access to this

deleteConfirmDlg() {
 $('.mini.modal')
  .modal({
    closable  : false,
    onDeny    : function(){
      window.alert('Wait not yet!');
      return false;
    },
    onApprove : () => {
      this.test();
    }
  }).modal('show');
 }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Once you get used to fat arrow functions, it's hard to ever want to use the function () { ... } form again. So. Much. Unnecessary. Typing. :-)
Yasss! Thank you. I thought the fat arrow was optional. You made my day!
the fat arrow function notation is the one that makes it possible to refer to component variables that we access via "this"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.