2

I have an angular2 component like this:

@Component({
    selector: 'demo',
    template: `
        <div [innerHTML]="content"></div>
    `;
})
export class demoComponent {
    @Input() step: string;

    private content: string = '';

    ngOnInit () {
        if (this.step === "foo") {
            this.content = "bar";
        }
    }
}

and I want to use some logic to decide on the most appropriate template to render. I have a series of static html files served by express on myDomain.com/templates. So I need to be able to "read" ./templates/xyz.html into a string in my ng2 component. Similarly to the fs.ReadFileSync API in nodeJS. How can I do this? HTTP call? file reader?

1 Answer 1

0

The short answer is that you can't read synchronously static files since they rely on an asynchronous API of the browser.

That being said, you could leverage a service to load all your resources and wait for this service to have loaded everything before starting your application. The APP_INITIALIZER service allows you to do that.

Here is a sample:

bootstrap(AppComponent, [
  { provide: APP_INITIALIZER,
    useFactory: (service:GlobalService) => () => service.load(),
    deps:[GlobalService, HTTP_PROVIDERS], multi: true
  }
]);

The load method would like something like that:

load():Promise<Site> {
  return new Promise(resolve => {
    this.http.get('somestaticfile.html')
      .map(res => res.text()    })
      .subscribe(text => {
        this.staticContent = text;
      });
  });
}

You can then use within your application the staticContent property synchronously:

@Component({
  selector: 'demo',
  template: `
    <div [innerHTML]="content"></div>
  `
})
export class demoComponent {
  @Input() step: string;

  private content: string;

  constructor(service:GlobalService) {
    this.content = service.staticContent;
  }
}

See this question for more details:

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much for this. In my application, I am only using this "demo" component in a subcomponent, which for most users will not get used, so I believe using this in the bootstrap will hold up every user whether they use the demo component or not? If that's correct, is there a way to only "hold up" the component that <demo> will be used in?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.