【问题标题】:Call index functions inside a component在组件内调用索引函数
【发布时间】:2017-12-10 09:11:42
【问题描述】:

我有一个 angular 4 应用程序,在 index.html 文件中,我在 ng 应用程序前后有很多 html 元素,因为它只是网站的一个小部件/组件。

在index文件的head部分,加载一些css和js库,如jquery、bootstrap等。

为了设置选择和选项标签的样式,我使用 bootstrap-select

问题是:在索引文件中硬编码的选择框可以正常工作,但 Angular 应用程序中的选择框只能在开始时工作。

如果我使用 *ngIf 指令隐藏和显示元素,当它再次添加时,它不会调用索引文件中的 2 个函数。

index.html

<script>
    $(document).ready(function(){
        if ($('.select_box').length > 0){initializeSelectPicker();}
    });

    $(window).load(function(){
        if ($('.select_box').length > 0){adjustSelectPicker();}
    });

    $(window).resize(function(){
        if ($('.select_box').length > 0){adjustSelectPicker();}
    });

    function initializeSelectPicker(){
        $('.select_box').selectpicker({});
    }

    function adjustSelectPicker(){

        $(this).find(".btn-group.bootstrap-select.select_box.show-tick .btn.dropdown-toggle.selectpicker.btn-default .filter-option.pull-left").css("width", "0");

        $(this).each(function(){
            var maxWidthBox = $(this).find(".btn-group.bootstrap-select.select_box.show-tick .btn.dropdown-toggle.selectpicker.btn-default").width() - 20;
            $(this).find(".btn-group.bootstrap-select.select_box.show-tick .btn.dropdown-toggle.selectpicker.btn-default .filter-option.pull-left").css("width", maxWidthBox + "px");
        });
    }
</script>

有没有办法在组件的ngOnChanges中调用它们?

【问题讨论】:

    标签: javascript angular typescript bootstrap-4 bootstrap-select


    【解决方案1】:

    我不推荐这种方法,但这可以通过发出事件并在索引文件中侦听所需的事件名称来解决。

    索引文件:

    window.addEventListener('ngFix', function(e) {
    // call either one of the methods you wish to run.
    });
    

    您必须在组件中的某个地方发出事件,大概是 if 指令的输入值发生更改的地方。

    window.dispatchEvent(new CustomEvent('ngFix'));
    

    【讨论】:

    • 谢谢@Shane van den Bogaard,你推荐的女巫方式?在具有相同功能的角度内使用引导程序?
    • 我建议使用 Angular 编写应用程序,而不仅仅是应用程序的某些部分。您可以在 Angular 组件中加载引导样式。我会将您尝试修复的那些元素包装在自定义组件中,并处理组件内的初始化和窗口大小调整。
    猜你喜欢
    • 2020-05-06
    • 2016-07-03
    • 2012-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-16
    • 2014-06-04
    • 2018-04-12
    相关资源
    最近更新 更多