Is it possible to import an HTML file as a string with TypeScript?

前端 未结 3 1517
天涯浪人
天涯浪人 2020-12-15 17:05

I wonder if it is possible to do as the title said.

For example let\'s say we are working on a Angular2 project and we want to avoid set the template as an external

相关标签:
3条回答
  • 2020-12-15 17:37

    Easiest answer:

    Use: templateUrl

    Example:

    @Component({
    selector: 'home',
    directives: [RouterLink],
    templateUrl: './template.html',
    })
    

    Note: the .html file have to be in the same component folder or you have to modify your path

    0 讨论(0)
  • 2020-12-15 17:41

    You can do this now:

    import "template.html";
    
    @Component({
      selector: 'home',
      directives: [RouterLink],
      template:  require("template.html"),
    })
    

    this will include "template.html" to the dependencies list of your component and then you can bundle it with your builder (actually, it makes more sense with amd)

    However, as you were suggested, it's better to use webpack.

    Take a look at this starter pack


    UPDATE now you can declare an html module like so:

    declare module "*.html" {
        const content: string;
        export default content;
    }
    

    and use it like so:

    import * as template from "template.html";
    
    @Component({
      selector: 'home',
      directives: [RouterLink],
      template: template
    })
    
    0 讨论(0)
  • 2020-12-15 18:00

    @Veikedo's answer above almost works; however the * as portion means that the entire module is assigned to the pointer template whereas we only want the content. The compiler error looks like this:

    ERROR in /raid/projects/pulse/angular-components/src/lib/card/card.ts (143,12): Argument of type '{ moduleId: string; selector: string; template: typeof '*.html'; encapsulation: ViewEncapsulation...' is not assignable to parameter of type 'Component'.
    

    The corrected import statement (at the time of writing, using TypeScript 2.3.3) is as follows:

    import template from "template.html";
    
    @Component({
      selector: 'home',
      directives: [RouterLink],
      template: template
    })
    
    0 讨论(0)
提交回复
热议问题