Snorlax
Snorlax

Reputation: 4765

Angular2, error when trying to add new module

I am trying to create a component called my-checklist, but I'm having issues running it.

I've declared the new module in app.ts as well as imported it, but it doesn't seem to be able to find my html file.

The error I get is:

zone.js:661 Unhandled Promise rejection: Failed to load checklist.component.html ; Zone: <root> ; Task: Promise.then ; Value: Failed to load checklist.component.html undefined

https://plnkr.co/edit/WZSc1X7whm658LEHidC4?p=preview

Upvotes: 0

Views: 222

Answers (2)

Swoox
Swoox

Reputation: 3740

The problem is in your app.ts.

You try to open your component but you link to the app your module can't find your html cause you link it to your app.ts not to your component.ts.

In your app.ts you say

bootstrap: [ App ]

It should be

bootstrap: [ MyCheckList ]

Try and follow https://angular.io/tutorial if not get it there a demos you can checkout.

Had some time made a plunker: https://plnkr.co/edit/1v0cd9y8BZ0KTQUDlhik?p=preview also note that plunker need src/*.html for some reason. normal you use ./ for that.

Upvotes: 1

Castro Roy
Castro Roy

Reputation: 7823

When trying to load checklist.component.html the URL is relative to your index.html and that is why it is failing. Just change it to

@Component({
  selector: 'my-checklist',
  templateUrl: 'src/checklist.component.html'
})

This will make it work. But, I'll recommend that you find out a way to convert your templates in a variable and avoid the relative path issue. I don't know typescript, but I know Babel do it, maybe this would work.

import template from './checklist.component.html';

@Component({
  template: template,
  selector: 'my-checklist'
})

For example, if using Babel, after transpiled the import will look like this

var template = '<p>Test</p>';

Awesome, eh?

Check this other questions, probably will help

Is it possible to import an HTML file as a string with TypeScript?
How to import external HTML files into a TypeScript class

Upvotes: 1

Related Questions