13

我有一个将函数作为输入的组件。我已经从父级传递了这个函数。

尽管调用了该函数,但该函数无法访问声明该函数的实例的依赖关系。

这是组件

@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

4

2 回答 2

39

.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>
于 2017-03-03T09:14:04.977 回答
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

于 2018-10-23T13:04:28.953 回答