我只是想知道是否有任何方式,形状或形式来引用在ngOnInit()中创建的函数,或者您可以创建某种形式的闭合来实现?
基本上:
component(){
somefunc()
//be able to call the function that's created in ngOnInit from the component via
//click event after the component renders
ngOnInit() {
function somefunc(){ ...whatever }
}
}
有没有办法做到这一点?
答案 0 :(得分:2)
可以通过将方法分配给var x = 10;
function outer () {
x = 20;
function inner () {
var x = x + 20;
return x;
}
inner();
}
outer();
var result = x;
中的类成员属性来完成。在下面的代码中,我将方法定义为箭头函数,以确保ngOnInit
引用方法主体中组件的实例。有关演示,请参见this stackblitz。
this
该方法然后可以用作事件处理程序:
export class AppComponent implements OnInit {
public onButtonClick: (event: Event) => void; // Member property will refer to the method
ngOnInit() {
let data = "And this comes from the closure!"; // Can be used inside of onButtonClick
// Assign the method to the member property
this.onButtonClick = (event: Event): void => {
console.log("The button was clicked!", data);
...
};
}
}
答案 1 :(得分:0)
您的伪语法有点混乱。
您可以像这样调用创建的函数:
import { Component, OnInit } from '@angular/core';
@Component({
templateUrl: './product-list.component.html',
styleUrls: ['./product-list.component.css']
})
export class ProductListComponent implements OnInit {
showImage = false;
constructor() {
}
ngOnInit(): void {
this.toggleImage();
}
toggleImage(): void {
this.showImage = !this.showImage;
}
}
您还可以通过如下按钮的点击事件来调用它:
<button class='btn btn-primary'
(click)='toggleImage()'>
Show Image
</button>
这是您要问的吗?