skip to Main Content

I’m building Angular 5 application which will be integrated with external CMS. That CMS have page templates which are rewrited to my Angular App. It’s working like on screen below:

Schema 1

Almost everything is working great, only I have problem with flickering. When I enter page for first time I can see one blink between Container and Layout load. See screen below :

Schema 2

Here is my code:

app.module.ts (route config)

const routes: Routes = [
  {
    path: '',
    pathMatch: 'full',
    redirectTo: '/pl'
  },
  {
    path: ':lang',
    component: ContainerComponent
  },
  {
    path: ':lang/:index',
    component: ContainerComponent,
  },
  {
    path: '**',
    component: NotfoundComponent
  }
];

container.component.ts

@Component({
  selector: 'app-container',
  templateUrl: './container.component.html',
  providers: [DownloadService, ServerService, Config, SeoService, LinkService],

})

export class ContainerComponent implements OnDestroy, AfterContentInit {
  subscription: ISubscription;
  lang: string;

  @ViewChild('container', { read: ViewContainerRef }) _vcr;


  constructor(@Inject(PLATFORM_ID) private platformId: Object, private link: LinkService, private componentFactoryResolver: ComponentFactoryResolver, private route: ActivatedRoute, private dl: DownloadService, private service: ServerService, private config: Config, private seo: SeoService) {
    if (isPlatformBrowser(this.platformId))
      this.getData();
  }

  ngOnInit() {
  }

  ngAfterContentInit() {
    this.subscription = this.route.params.subscribe((params) => {
      this.getLayoutData(params);
    })
  }

  ngOnDestroy() {
    if (this.subscription) this.subscription.unsubscribe();
  }

  generateSeo(seoData: Seo, langURL, index) {
    let title = '';

    if (seoData.metaTitle == '')
      title = seoData.title;
    else
      title = seoData.metaTitle;

    this.link.addTag({ rel: 'canonical', href: `${this.config.URL}/${langURL}/${index}` });
    this.seo.generateTags({ lang: langURL, title: title, description: seoData.description, keywords: seoData.keywords, image: seoData.banner, slug: index })
  }

  getLayout(index): Type<any> {
    switch (index) {
      case 'HomeComponent': return HomeComponent
      case 'MainComponent': return MainComponent
      case 'NewsComponent': return NewsComponent
      default: return MainComponent
    }
  }

  getLayoutData(params) {
    let index = '';

    if (typeof params.index === 'undefined') index = 'home';
    else index = params.index;

    if (typeof params.lang === 'undefined') this.lang = this.config.getLanguage();
    else this.lang = params.lang;

    this.subscription = this.service.getResponse(`${this.config.impressURL}/api/seo/${index}/${this.lang}`).subscribe(response => {
      this.generateSeo(response, this.lang, index);
    }, (error) => {
      console.log(error);
    });


    if (isPlatformBrowser(this.platformId))
      this.subscription = this.service.getResponse(`${this.config.impressURL}/api/layout/${index}/${this.lang}`).subscribe(res => {
        this.getComponent(res);
      }, (error) => {
        this.dl.getLayout(URL, index, params.lang).then((res: any) => {
          this.getComponent(res);
        });
      });

    if (isPlatformServer(this.platformId))
      this.subscription = this.service.getResponse(`${this.config.impressURL}/api/layout/${index}/${this.lang}`).subscribe(res => {
        this.getComponent(res);
      });
  }

  getComponent(layout) {
    let component = this.getLayout(layout);
    let componentFactory = this.componentFactoryResolver.resolveComponentFactory(component);
    let viewContainerRef = this._vcr;
    viewContainerRef.clear();
    let componentRef = viewContainerRef.createComponent(componentFactory);
  }

  async getData() {
    await this.dl.downloadDataInBackground(this.config.impressURL);
  }

}

container.component.html

<div class="mainContainer">
  <div #container></div>
</div>

app.component.html

<app-menu></app-menu>

<main class="main-content">
  <router-outlet></router-outlet>
</main>

<app-footer></app-footer>

EDIT 11:04 04.04.2018 – container.component.html

Now container.component.html looks like

<div class="mainContainer">
  <ng-template #container [ngIf]="layout"></ng-template>
</div>

Do you know how to solve it ?

2

Answers


  1. Chosen as BEST ANSWER

    Finally I found the solution.

    That part of code:

     getComponent(layout) {
        let component = this.getLayout(layout);
        let componentFactory = this.componentFactoryResolver.resolveComponentFactory(component);
        let viewContainerRef = this._vcr;
        viewContainerRef.clear();
        let componentRef = viewContainerRef.createComponent(componentFactory);
    

    Changed to :

      getComponent(layout) {
        let component = this.getLayout(layout);
        let componentFactory = this.componentFactoryResolver.resolveComponentFactory(component);
        let componentRef = this._vcr.createComponent(componentFactory);
      }
    

    And inside router subscriber I am clearing View Container so my previous code:

      ngAfterContentInit() {
        this.subscription = this.route.params.subscribe((params) => {
          this.getLayoutData(params);
        })
      }
    

    Looks now:

      ngAfterContentInit() {
        this.subscription = this.route.params.subscribe((params) => {
          this._vcr.clear();
          this.getLayoutData(params);
        })
      }
    

  2. I did a modal a few days ago and had a similar problem you described in the comment section.

    When you use *ngIf over you ViewContainerRef it is then undefined and you get the error:

    ERROR TypeError: Cannot read property 'clear' of undefined.

    What you can do however is to have a component in between.

    In my case my dialog container looked like this

    <div class="modal" *ngIf="isOpen">
        <ng-template dialogHostApp></ng-template>
    </div >
    

    I had to do that

    <!-- we have to use another component to wrap the template else the viewcontainer is gonna be undefined-->
    <dialog-modal-app [isOpen]="isOpen">
        <ng-template dialogHostApp></ng-template>
    </dialog-modal-app>
    

    and in my modal component

    <div *ngIf="isOpen" class="modal">
        <ng-content></ng-content>
    <div>
    

    In your case that would translate to, instead of this :

    <div class="mainContainer">
      <ng-template #container [ngIf]="layout"></ng-template>
    </div>
    

    You could have this

    <main-container-app [isShown]="layout">
      <ng-template #container></ng-template>
    </main-container-app>
    

    and in the main-container-app

    <div *ngIf="isOpen" class="mainContainer">
        <ng-content></ng-content>
    <div>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search