chitakuma
chitakuma

Reputation: 329

Alternatives to $templateCache in Angular2

When we think of using template in Angular2 or Angular1.X, we know below is one of the basic way of writing:

template: './template-ninja.html'

and with Angular1.X, we can previously cache all of templates with $templateCache.put() as follows:

var myApp = angular.module('Ninja', []);
myApp.run(function($templateCache) {
  $templateCache.put('templateNinja.html', 'This is the content of the template-ninja');
});

which will lessen the number of http requests. I'd like to know how can I implement the same with Angular2. Could anyone help? Thanks.

Upvotes: 13

Views: 5934

Answers (4)

Paul Sweatte
Paul Sweatte

Reputation: 24637

Use the following alternative:

  • Import RuntimeCompiler, reflector, ComponentFactory, ComponentResolver, ReflectorComponentResolver, and ReflectionInfo
  • Inject RuntimeCompiler
  • Create a ComponentResolver instance
  • Invoke ComponentResolver.resolveComponent(SomeComponent)
  • Check reflector.propMetadata for the cached result
    it('should cache the result', inject([AsyncTestCompleter], (async) => {
         PromiseWrapper
             .all([ComponentResolver.resolveComponent(SomeComponent), ComponentResolver.resolveComponent(SomeComponent)])
             .then((protoViewRefs) => {
               expect(protoViewRefs[0]).toBe(protoViewRefs[1]);
               async.done();
             });
       }));

Annotation is the other way to do it:

    it('should read the template from an annotation',
       inject([AsyncTestCompleter, Compiler], (async, compiler) => {
         ComponentResolver.resolveComponent(SomeComponent)
             .then((hostViewFactoryRef) => {
               expect(hostViewFactoryRef.internalHostViewFactory).toBe(someHostViewFactory);
               async.done();
             });
       }));

References

Upvotes: 2

Evgeny Sorokin
Evgeny Sorokin

Reputation: 730

gulp-ng2-template-wrap

Hi,

Hope this will be helpful to you: I just wrote a small module that allows you to bundle all of your html files into single ES6 module.

https://github.com/evgenys91/gulp-ng2-template-wrap

Upvotes: 2

superluminary
superluminary

Reputation: 49232

gulp-inline-ng2-template

Currently the best solution is gulp-inline-ng2-template.

This takes a component with a templateUrl attribute, plus an html file, and turns it into a component with an inlined template.

https://github.com/ludohenin/gulp-inline-ng2-template

Upvotes: 4

Jeremy Wilken
Jeremy Wilken

Reputation: 6974

I don't know of a library or tool that will cache templates for Angular 2 yet, but so far, I have been happy to just use inline templates instead of external files. Using the es6 backtick character for a template, it allows you to write multiline HTML in the JavaScript and keeps everything in one file.

https://github.com/angular-in-action/chapter2/blob/master/client/components/dashboard.ts#L12

Upvotes: 2

Related Questions