Search code examples
angularsystemjs

html template file isn't found Angular 5


I have Angular 5 app with systemjs.config.js file.

Structure of files is the following: app folder contains main.ts, app.compoment.ts, app.component.html, app.module.ts, app-routing.module.ts files.

systemjs.config.js:

paths: {
    'npm:': "libs/"
},
map: {
    app: "app",
    ...
},
packages: {
    app: {
        main: "./main.js",
        defaultExtension: "js"
    },
    ...
}

When I put path as relative:

templateUrl: './app.component.html'

I have error {domain}/app.component.html not found. {domain} = http://localhost:1234

But if I put absolute path:

templateUrl: './app/app.component.html'

it works fine.

What should I do to get relative paths working?


Solution

  • Added SystemJS plugin (systemjs-angular-loader.js) to SystemJS configuration. This plugin dynamically converts "component-relative" paths in templateUrl and styleUrls to "absolute paths" for you.

    I strongly encourage you to only write component-relative paths. You no longer need to write @Component({ moduleId: module.id }), nor should you.

    angular quickstart

    meta: {
      './*.js': {
        loader: 'systemjs-angular-loader.js'
      }
    }
    

    systemjs.config

    angular-cli

    To align with @angular/core behavior, all templateUrl and styleUrls are now treated as relative - developers should use the ./foo.html form in all cases.

    See also

    Relative template and style urls using system js without moduleid in angular

    PREVIOUS VERSION

    By default, you should specify the full path back to the application root. It is absolute with respect to the application root.

    It may be:

    @Component({
       templateUrl: 'app/app.template.html' // or src
    })
    export class AppComponent {}
    

    If you want to specify template and style URLs relative to their component class files you should set moduleId property to decorator of your component:

    @Component({
      moduleId: module.id
      templateUrl: './app.template.html'
    })
    export class AppComponent {}
    

    If you use SystemJS, then it should be __moduleName variable instead of the module.id variable:

    @Component({
      moduleId: __moduleName,
      templateUrl: './app.template.html'
    })
    export class AppComponent {}
    

    Component relative paths in angular