开发者问题收集

访问 Angular 7 中的函数

2018-10-25
3165

在我的组件类 (HeaderComponent) 中, 每次单击两个函数 changeBannerArrow() 和 changeBannerImg() 时,我都想访问 changeBtnColorBg 函数

这些函数在 HTML 端的 onclick 事件上触发

export class HeaderComponent implements OnInit {
    imgTotal = 3;
    currentImg = 0;

    imgHdr = [];

    changeBannerImg(imgSelect){
        /* some code here */
        changeBtnColorBg(this.currentImg, imgSelect);
    }


    changeBannerArrow(imgSelect){
        from = this.currentImg;

        /* some code here*/
        to = this.currentImg;

        changeBtnColorBg(from, to);

    }

    changeBtnColorBg(from, to){
        this.imgHdr[from].selected = false; //change back to transparent

        this.imgHdr[to].selected = true; //change bg color
    }
}

但是此结构会产生错误

HeaderComponent.html:15 ERROR ReferenceError: changeBtnColorBg is not defined

有人可以帮忙吗?我是新手

3个回答

似乎您在 changeBannerArrowchangeBannerImg 方法中遗漏了 this

  changeBannerArrow(imgSelect){
        from = this.currentImg;

        /* some code here*/
        to = this.currentImg;

        this.changeBtnColorBg(from, to);
}


   changeBannerImg(imgSelect){
        /* some code here */
        this.changeBtnColorBg(this.currentImg, imgSelect);
    }
SMH
2018-10-25
changeBtnColorBg(this.currentImg, imgSelect);

this.changeBtnColorBg(this.currentImg, imgSelect); // add 'this'
Franklin Pious
2018-10-25

尝试进行以下更改:

export class HeaderComponent implements OnInit {
imgTotal = 3;
currentImg = 0;

imgHdr = [];

changeBannerImg(imgSelect){
    /* some code here */
    this.changeBtnColorBg(this.currentImg, imgSelect); // make change here
}


changeBannerArrow(imgSelect){
    from = this.currentImg;

    /* some code here*/
    to = this.currentImg;

    this.changeBtnColorBg(from, to); // make change here

}

changeBtnColorBg(from, to){
    this.imgHdr[from].selected = false; //change back to transparent

    this.imgHdr[to].selected = true; //change bg color
}

>

Sarthak Aggarwal
2018-10-25