Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
825 views
in Technique[技术] by (71.8m points)

angular - Differences of using Component template vs templateUrl

Angular 2 allows to write multi-line templates by using ` characters to enquote them. It is also possible to put multi-line template into .html file and reference it by templateUrl.

It seems comfortable for me to put the template directly into component as then it's all in one place, but is there any drawback of doing so?

1st approach:

import {Component} from 'angular2/core';
@Component({
    selector: 'my-app',
    template: `
    <h1>My First Angular 2 multiline template</h1>
    <p>Second line</p> 
    `
})
export class AppComponent { }

vs 2nd approach:

import {Component} from 'angular2/core';
@Component({
    selector: 'my-app',
    templateUrl: 'multi-line.html'
})
export class AppComponent { }

together with multi-line.html:

<h1>My First Angular 2 multiline template</h1>
<p>Second line</p> 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In terms of how the final application will perform, there's no real difference between having an embedded template and an external template.

For the developer, however, there are a number of differences that you have to consider.

  1. You get better code completion and inline support in your editor/IDE in most cases when the HTML is in a separate .html file. (IntelliJ IDEA, at least, supports HTML for inline templates and strings)
  2. There is a convenience factor to having code and the associated HTML in the same file. It's easier to see how the two relate to each other.

These two things will be of equal value for many people, so you'd just pick your favorite and move ahead with life if this were all there was to it.

But that leads us to the reasons you should keep your templates in your components, in my opinion:

  1. It is difficult to make use of relative filepaths for external templates as it currently stands in Angular 2.
  2. Using non-relative paths for external templates makes your components far less portable, since you need to manage all of the /where/is/my/template type references from the root that change depending on how deep your component is.

That's why I would suggest that you keep your templates inside your components where they are easily found. Also, if you find that your inline template is getting large and unwieldy, then it is probably a sign that you should be breaking your component down into several smaller components, anyway.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...