如何将角度指令绑定到当前路径

时间:2018-10-29 09:03:12

标签: angular directive

我有以下指令,我想基于当前页面隐藏/显示元素。该指令仅适用于页面首次加载。通过链接导航到其他页面时无法正常工作。所以问题是指令不会通过url事件更新。 请注意,该指令当前已附加到headerComponent,该标题始终可见,并且在导航到其他页面时不会更改

    @Directive(
    { selector: '[ngIfPage]',  })
export class NgIfCurrentPageDirective {
    private currentPath: string;
    constructor(
        private templateRef: TemplateRef<any>,
        private viewContainer: ViewContainerRef,
        private router: Router) {
        this.currentPath = this.router.url;

        this.router.events.subscribe(() => {
            if (event instanceof NavigationEnd) {
                this.currentPath = this.router.url;
            }

        });
    }


    @Input('ngIfPage') set pageName(option) {
        if (this.shouldDisplayElement(option)) {

            this.viewContainer.createEmbeddedView(this.templateRef);
        } else {
            this.viewContainer.clear();
        }
    }


    shouldDisplayElement(option) {
        switch (option) {
            case Pages.WorkflowList: {
                return this.testRegxPattern('\/some-page\/?$');
            }

            case Pages.Workflow: {
                return this.testRegxPattern('\/some-page\/.+');
            }

            default: {
                return false;
            }
        }
    }

    testRegxPattern(pattern: string) {
        const regExp = new RegExp(pattern);
        return regExp.test(this.currentPath);
    }
}

0 个答案:

没有答案