加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

使用回调函数作为组件@Input()时的Angular2 Undefined Object属

发布时间:2020-12-17 17:58:28 所属栏目:安全 来源:网络整理
导读:我试图将回调函数绑定到一个指令,当事件被触发时,父组件的属性是未定义的 app.ts import {Component} from 'angular2/core';import {bootstrap} from 'angular2/platform/browser';import {MyComponent} from './my-component';@Component({ selector: 'my-a
我试图将回调函数绑定到一个指令,当事件被触发时,父组件的属性是未定义的

app.ts

import {Component} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';
import {MyComponent} from './my-component';

@Component({
  selector: 'my-app',template: `
  <button (click)="appOnClick('CLICK FROM APP')">BUTTOM OUTSIDE COMPONENT</button>
  <br><br>
  <my-component [onClick]="appOnClick"></my-component>`,directives: [MyComponent]
})
export class MyApp { 

  public theBoundCallback: Function;
  test:string = "THIS SHOULD HAVE A VALUE";

  public ngOnInit(){
    this.theBoundCallback = this.appOnClick.bind(this);
  }

  appOnClick(someText){

    console.log(someText);
    console.log(this.test);

  }
}

bootstrap(MyApp);

我-component.ts

import {Component,Input} from 'angular2/core';

@Component({
  selector: 'my-component',template: `<button (click)="onClick('CLICK FROM COMPONENT')">BUTTOM INSIDE COMPONENT</button>`
})
export class MyComponent{

  @Input() onClick: Function;

}

这将呈现两个按钮:

BUTTOM OUTSIDE COMPONENT,直接从应用程序调用appOnClick函数,当点击控制台显示:
– 点击APP
– 这应该有价值

BUTTOM INSIDE COMPONENT,它通过组件中的@Input函数调用appOnClick函数,单击时控制台显示:
– 点击APP
– 未定义

我在Plunker上创建了这个例子

这是一种正确分配这种方式的方法,这样当触发回调时我可以使用我的对象属性吗?

解决方法

Updated plunkr

为了以这种方式传递appOnClick,你需要将它声明为如下属性:

export class MyApp {
  ...
  appOnClick = (someText) => {
    console.log(someText);
    console.log(this.test);
  }
}

代替:

export class MyApp {
  ...
  appOnClick(someText){
    console.log(someText);
    console.log(this.test);
  }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读