Angular 2 - The component template
When angular finds a match in the DOM for
a component selector, it will inject the component markup into that DOM
element that it found a match on.
The markup it will inject comes from the
component metadata template properties.
There are two options, the template, and the templateUrl.
For Ex: In the app component, we can see that it
is using the template property and setting it to a string value of some
markup. This is an inline template. The markup is declared within the
component metadata. If we switch over to the browser, and take a look at
the run time results by inspecting the DOM, we can see that the
element named mw-app has the
markup from the metadata inserted inside of it. Back in the code, we
can change that markup in the template metadata property. Add some
new content, like a p tag, with a description of what the media tracker
app is all about, and when the browser reloads, we can see that
our new content is there.
Using
template:
import { Component } from
'@angular/core';
@Component({
selector: 'app',
template: '<h1>My
App</h1>'
})
export class AppComponent {}
Using the template metadata property is an
easy way to compose our angular components. And since we are writing our
JavaScript using TypeScript, we can leverage future forward
syntax, like the back tick to surround strings. ES2015 has support
for back ticks which allow multi-line string definitions in
JavaScript. So, we can use back ticks around the template value, and
start moving things to multiple lines for better readability. The
other metadata property we can use is the templateUrl. This
property allows us to specify a file that contains the template
content. Angular will load that template file for us, and do the same
content injection. We can create a new file named
app.component.html in the app folder to hold the template. And we can
grab the markup from the template property and paste it into the new
file. Then we can go back to the app.component.ts
file and change the template property to be templateUrl. And give it the path to the app.component.html file we just created. Now this path is
the relative path to the file from the base path of the web
application served up by the web server. For this project, the web
server is serving the files out of the root folder. Thus, the web
path in this case is app/app.component.html.
Using
templateUrl :
import { Component } from
'@angular/core';
@Component({
selector: 'mw-app',
templateUrl: 'app/app.component.html'
})
export class AppComponent {}