Angular - 2-8 Working with component templates
So far every component we built relied on an external template file referenced through templateUrl. That is the cleanest setup most of the time, but Angular also accepts inline templates declared directly in the TypeScript file. Both options are valid — you just have to pick one per component, because every component must have exactly one template defined somewhere.
To switch from an external file to an inline template, open server.component.ts and replace the templateUrl key with template. The value becomes a plain string holding the HTML. For a single line, regular single quotes are enough, but as soon as you want multiline HTML — which is almost always the case — switch the string delimiters to backticks. ES6 template literals make it trivial to spread the markup over several lines and even to interpolate values later on.
@Component({
selector: 'app-server',
template: `
<app-server></app-server>
<app-server></app-server>
`
})
export class ServerComponent {}
After saving, the browser shows exactly the same result as before: from the user's point of view nothing has changed, but the way you configure the component is now slightly different. Which approach should you favour? If the template is small — a handful of elements — an inline template keeps everything close together and is perfectly fine. As soon as you reach three lines of HTML or more, the external file becomes a lot easier to read, format and refactor.
There are two takeaways worth remembering. First, both template and templateUrl are accepted but only one at a time. Second, the template is the only piece a component must have. The selector can be omitted (you will see why when we cover routing) and styles are optional, but without a template Angular cannot render anything. In the next lesson we will look at the styling side, which follows the same dual configuration model.