5

I'm using Angular 9.1.3 and Typescript 3.8.3.

I want to import html file as a raw string.

For the case:

import * as template from "./projects.page.html";
console.log("Template: ", template);

I'm getting error:

ERROR in src/app/features/projects/projects.page.ts:41:27 - error TS2307: Cannot find module './projects.page.html'.

41 import * as template from "./projects.page.html";

If I add html.d.ts file:

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

I'm getting error:

ERROR in ./src/app/features/projects/projects.page.html 1:0
Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
> <div style="height: calc(100vh - 64px)">
3
  • If you just want to get the component's html in ts code, you can get it with ViewChild reference ex: ` @ViewChild('abc', { read: ElementRef, static: true }) htmlRef: ElementRef; htmlRef.nativeElement.innerHTML` should give you the component's html. Commented Jun 3, 2020 at 5:30
  • I don't want to include it into the DOM for reading later... Commented Jun 3, 2020 at 5:33
  • You will need raw-loader webpack for this, which will convert a text file into a javascript module Commented Jun 3, 2020 at 6:58

2 Answers 2

9

I had the same problem and I fixed it using the html template inside a typescript file.

You could create a template.ts file like this:

const template = `
  <div> Your template here! </div> 
`;

export default template;

And you could simply import the file in this way :

import template from "./template";
Sign up to request clarification or add additional context in comments.

1 Comment

Yep, this will definitely work but it's not what I'm looking for...
4

As mention @htn in the comment - will need raw-loader webpack for this.

npm i -D @angular-builders/custom-webpack
npm i -D raw-loader

Update angular.json

"architect": {
    "build": {
        "builder": "@angular-builders/custom-webpack:browser",
        "options": {
            "customWebpackConfig": {
                "path": "./webpack.config.js"
            },
            ...
        }
    }
}
...

"serve": {
    "builder": "@angular-builders/custom-webpack:dev-server",
    "options": {
        "customWebpackConfig": {
            "path": "./webpack.config.js"
        },
        "browserTarget": "okwiki:build",
        ...
    }
}
...

Add html.d.ts:

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

And it works:

import template from "./projects.page.html";
console.log("Template: " + template);

Comments

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.