Angular2传递函数作为组件输入不起作用

时间:2017-03-03 09:10:58

标签: angular angular2-template angular2-di

我是一个以功能为输入的组件。我已从父母传递此功能。

虽然调用了该函数,但该函数无法访问声明此函数的实例的依赖项。

这是组件

@Component({
  selector: 'custom-element',
  template: `
    {{val}}
  `
})
export class CustomElement {
  @Input() valFn: () => string;

  get val(): string {
    return this.valFn();
  }
}

以下是组件的使用方式

@Injectable()
export class CustomService {
  getVal(): string {
    return 'Hello world';
  }
}

@Component({
  selector: 'my-app',
  template: `
   <custom-element [valFn]="customVal"></custom-element>
  `,
})
export class App {
  constructor(private service: CustomService) {
  }
  customVal(): string {
    return this.service.getVal();
  }
}

当我运行此应用时,我在控制台中收到错误Cannot read property 'getVal' of undefined

这是一个问题的掠夺者。

https://plnkr.co/edit/oQ229rXqOU9Zu1wQx18b?p=preview

2 个答案:

答案 0 :(得分:17)

如果您传递方法,则需要.bind(this)

<custom-element [valFn]="customVal.bind(this)"></custom-element>

export class App {
  constructor(private service: CustomService) {
  }
  customVal(): string {
    return this.service.getVal();
  }
  customValFn = this.customVal.bind(this);
}

<custom-element [valFn]="customValFn"></custom-element>

答案 1 :(得分:1)

您可以通过类似的方式传递get / set属性而不是函数:

您认为的某个地方:

<input type="text" [(ngModel)]="yourprop">

在您的组件文件中:

@Component({
  selector: 'myapp',
  templateUrl: './myapp.component.html',
  styleUrls: ['./myapp.component.scss']
})
export class App {
  constructor() { }

  yourprop: any;

  get yourprop(): any {
    return this.scheduleEndDate;
  };

  //set accessor including call the onchange callback
  set yourprop(v: any) {
    // TODO do something else
    // You can do whatever you want just like you have passed a function

    if (v !== this.scheduleEndDate) {
      this.scheduleEndDate = v;
    }
  }

}

更多信息@ https://almerosteyn.com/2016/04/linkup-custom-control-to-ngcontrol-ngmodel

相关问题