作为参考传递的Angular 5/4/2方法不在范围内

时间:2018-02-01 07:23:47

标签: angular

Run the entire example

我有一个简单的模块,我称之为:

<app-button [(registerOnClickEvent)]="alertTest" ></app-button>

模块正在内部监听点击事件并在外面传递到alertTest

@Component({
  selector: 'app-button',
  template: '<button (click)="passTheClickEvent($event)"  value="test"  >Click</button>',
})
export class ButtonComponent    {
  @Input() 
  registerOnClickEvent : Function = new Function();

  passTheClickEvent(){
    this.registerOnClickEvent();
  }
}

alertTest内,appModel未定义:

export class AppComponent  {
  appModel : AppModel = {name : "Ron Howard"};
  alertTest(){
    console.log(this.appModel); // this.appModel us undefined
    alert("test");
  }
}

我不明白为什么?我正在发起它:

appModel : AppModel = {name : "Ron Howard"};

Run the entire example

2 个答案:

答案 0 :(得分:3)

您必须使用箭头功能来实现此目的

工作示例: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);
   }
}

要了解有关箭头功能的更多信息,请参阅mozilla documentation link

  

箭头函数表达式的语法短于函数   表达式并没有自己的this,arguments,super或者   new.target。这些函数表达式最适合非方法   函数,它们不能用作构造函数。

     

在箭头函数之前,每个新函数都定义了自己的这个值   (构造函数中的新对象,在严格模式下未定义)   函数调用,如果函数被调用为基础对象   “对象方法”等)。事实证明这不太理想   面向对象的编程风格。

答案 1 :(得分:2)

@ Paritosh的回答是正确的,我建议这样做。我只想提出另一种(更老的?)方法。当您将这样的函数传递给另一个组件时,DateTime dateTime = DateTime.Now; string strDateTime = string.Format("{0:000}{1:00}{2:00}{3:00}{4:00}", dateTime.Year - 1911, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute); string SQL2 = "update \"UserProfile1\" set \"chLogInDT\" = :strDateTime, \"chLogOutDT\" = :strDateTime2, \"chUserSector\" = '電子書',\"chLogInStat\" = :aIP where RTrim(\"chUserID\") = :chUserID "; Conn.Open(); using (var cmdQry2 = Conn.CreateCommand()) { string ip = CommonUse.GetIPAddress(); cmdQry2.CommandText = SQL2; cmdQry2.CommandType = CommandType.Text; cmdQry2.Parameters.Add("chUserID", this.txtAccount.Text.Trim()); cmdQry2.Parameters.Add("strDateTime", strDateTime); cmdQry2.Parameters.Add("strDateTime2", strDateTime); cmdQry2.Parameters.Add("aIP", ip); try { int n = cmdQry2.ExecuteNonQuery(); Conn.Close(); } catch (Exception ex) { Debug.WriteLine(ex.Message); } } 的范围会有所不同。

您可以将范围从AppComponent绑定到这样的方法:

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"); } } 传递给alertTestScoped组件。

Working example