【问题标题】:Angular2 Undefined Object attribute when using a callback function as Component @Input()使用回调函数作为组件@Input()时的Angular2未定义对象属性
【发布时间】:2016-07-22 17:40:06
【问题描述】:

我试图将回调函数绑定到指令,当事件被触发时,父组件的属性是未定义的

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);

我的组件.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;
  
}

这将呈现两个按钮:

按钮外部组件,这会直接从应用程序调用 appOnClick 函数,单击时控制台显示:
- 从应用程序点击
- 这应该有一个价值

BUTTOM INSIDE COMPONENT,这通过组件中的@Input函数调用appOnClick函数,点击时控制台显示:
- 从应用程序点击
- 不明确的

我在Plunker上创建了示例

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

【问题讨论】:

    标签: callback typescript angular


    【解决方案1】:

    我认为您在使用 appOnClick 方法时忘记了“(...)”,而在配置事件处理程序时使用了“[...]”而不是“(...)”:

    <my-component (onClick)="appOnClick($event)"></my-component>`,
    

    此外,在您的子组件中,您需要使用“@Output”定义一个自定义事件:

    @Component({
      selector: 'my-component',
      template: `<button (click)="handleClick('CLICK FROM COMPONENT')">BUTTOM INSIDE COMPONENT</button>`
    })
    export class MyComponent{
      @Output()
      onClick:EventEmitter<string> = new EventEmitter();
    
      handleClick(txt:string) {
        this.onClick.emit(txt);
      }     
    }
    

    【讨论】:

      【解决方案2】:

      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);
        }
      } 
      

      【讨论】:

      • @Mush - 没问题 :-) 如果这个答案解决了问题,请考虑接受它
      • 谢谢你的drawmoore,一直在敲我的头,为什么我不能访问这个。
      猜你喜欢
      • 2016-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多