JayChase / angular2-highlight-js

highlight.js integration with Angular
MIT License
21 stars 9 forks source link

ngAfterViewChecked doesn't fire on directive #17

Closed RyanClementsHax closed 6 years ago

RyanClementsHax commented 6 years ago

When implementing this directive verbatim how the demo describes, the lifecycle hook ngAfterViewChecked() {...} doesn't fire. After a quick search, it doesn't fire because directives don't have that hook because they don't have a view. As a result the code calling hljs.highlightBlock(snippet); never gets called.

Here is the relevant code:

ngAfterViewChecked() {
        if (!this.done) {
            const selector = this.highlightSelector || 'code';

            if (this.elementRef.nativeElement.innerHTML && this.elementRef.nativeElement.querySelector) {
                const snippets = this.elementRef.nativeElement.querySelectorAll(selector);
                this.zone.runOutsideAngular(() => {
                    for (const snippet of snippets) {
                        hljs.highlightBlock(snippet);
                    }
                });

                this.done = true;
            }
        }
    }

Any thoughts/solutions?

JayChase commented 6 years ago

Hi. Directives support the same life cycle hooks as components in Angular https://angular.io/guide/lifecycle-hooks.

RyanClementsHax commented 6 years ago

You're right, my bad