Angular 5/4/2 method passed as reference is not in scope

后端 未结 2 1627
自闭症患者
自闭症患者 2021-01-23 16:59

Run the entire example

I have a simple module that I call it as the following:



        
相关标签:
2条回答
  • 2021-01-23 17:47

    @Paritosh's answer is correct and I recommend doing it like that. I just want to propse yet another (older?) method of doing it. The scope for this is different when you pass the function like that to another component.

    You could bind the scope from AppComponent to the method like this:

    export class AppComponent  {
      appModel : AppModel = {name : "Ron Howard"};
      // bind scope from AppCompoent to the method, making this being the scope from this component, and not from ButtonComponent 
      alertTestScoped:Function = this.alertTest.bind(this); 
      alertTest(){
        console.log(this.appModel); // this.appModel us undefined
        alert("test");
      }
    
    }
    

    and then pass alertTestScoped to the AppButton component.

    Working example

    0 讨论(0)
  • 2021-01-23 17:56

    You have to use arrow function to achieve this

    Working example: https://stackblitz.com/edit/angular-hbfhxu?file=app/app.component.ts

    export class AppComponent  {
       appModel : AppModel = {name : "Ron Howard"};
    
       // convert the function into arrow function
       alertTest = () => {
          console.log(this.appModel);
          alert(this.appModel);
       }
    }
    

    To know more on Arrow function, here is the mozilla documentation link

    An arrow function expression has a shorter syntax than a function expression and does not have its own this, arguments, super, or new.target. These function expressions are best suited for non-method functions, and they cannot be used as constructors.

    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.

    0 讨论(0)
提交回复
热议问题