Angular isPlatformBrowser checking against PLATFORM_ID doesn't prevent server-side pre rendering

后端 未结 1 780
故里飘歌
故里飘歌 2020-12-18 23:07

I am trying to compile Angular 4 + ASP.NET Universal application created based on sample project here, using this hints https://github.com/angular/universal#universal-gotcha

相关标签:
1条回答
  • 2020-12-19 00:03

    You can remove some elements from your DOM by using *ngIf. Write the current state into a property of your component and check this within your html file.

    component.ts

    import { Component, Inject } from '@angular/core';
    import { PLATFORM_ID } from '@angular/core';
    import { isPlatformBrowser } from '@angular/common';
    
    @Component({
      selector: 'mySpecial',
      templateUrl: './mySpecial.component.html'
    })
    export class MySpecialComponent {
      isBrowser: boolean;
    
      constructor( @Inject(PLATFORM_ID) platformId: Object) {
        this.isBrowser = isPlatformBrowser(platformId);
      }
    }
    

    component.html

    <h2>Hello World</h2>
    <p>
      <md-select *ngIf="isBrowser" placeholder="Favorite food" name="food">
        <md-option value="Steak">Steak</md-option>
        <md-option value="Pizza">Pizza</md-option>
        <md-option value="Tacos">Tacos</md-option>
      </md-select>
    </p>
    

    This will on the server side create a DOM that doesn't contain md-select and so doesn't fail. But be aware that this could lead to some unexpected changes of what the user sees, cause the site will first be rendered in the browser without the element (cause that's what the server delivered) and after javascript is loaded and angular took into action the element suddenly appears.

    0 讨论(0)
提交回复
热议问题