1

I'm refactoring an Angular 2 component that does some template nesting.

The original code was something like this:

(component.ts)

let subItemTemplate = require('./sub-item-template.html');

@Component({
selector: 'my-component',
template: `
  <div *ngIf="isSingle">
    ${subItemTemplate}
  </div>
  <div *ngIf="isMulti">
    ${subItemTemplate}
  </div>
`
})
export default class MyComponent{
}

With an inline template, this works great - the string interpolation for my subItemTemplate is successfully parsed and my component works.

When I move the component template into an external file, this stops working:

let subItemTemplate = require('./sub-item-template.html');

@Component({
selector: 'my-component',
template: require('./my.component.html')
})
export default class MyComponent{
}

Now I get a runtime exception in my browser:

zone.min.js:1 Unhandled Promise rejection: Template parse errors: Unexpected character "EOF" (Do you have an unescaped "{" in your template? Use "{{ '{' }}") to escape it.) ("

The only change is from moving my template to an external file.

I'm thinking this can be one of 2 major issues. Either it's an Angular limitation I'm not understanding, or Angular is a red herring and this is actually an issue in my compilation scripts (ultimately bundling with browserify).

1 Answer 1

1

You seem to do the wrong way.

In the first way, you write template via string and import sub-template like a string. With string interpolation, you concat. template with sub-template, and then Angular 2 parse the result when you load the component.

In the second way, your template is import and served to Angular 2. But sub-template is alone and never used/concat.

Why you need to add a sub-template in your component ?

Because the sub-template is requiered in this component ?

So, make a sub-component with template, and use it your parent component, it's readable and easy.

If you need to pass data or event, check @Input and @Output decorator.

If you really need to add a sub-template, they've many way to do this like @ViewChild. Check Angular 2 documentation.

Sign up to request clarification or add additional context in comments.

1 Comment

I agree - thanks for explaining how the template construction works. For my question, the sub-template import was done only to prevent duplication of the code in 2 places of the main template. I've moved that template into a standalone sub-component and not only does it work correctly, it actually looks like a sane ng2 component now.

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.