Learn how to define HTML inline and externally within the component decorator metadata.
- [Instructor] Angular offers two ways to define HTML. You can write inline HTML within the template property of the component decorator, or you could place all the HTML for a given component within it's own HTML file, with a path defined by the template URL property of the component decorator. Now, generally speaking, if you are working with a component that a lot of HTML, it's worth placing all of that HTML inside of it's own template file. Otherwise, your component file may become quite cluttered with a lot of HTML in the component decorator.
Ultimately, where you place the HTML, whether that be inline or in its own template file, is up to you. Now let's take a quick look at our project and how both of these templating methods work. By default, the angular command line interface defines a template URL property to designate an HTML file. We can see that on line five. If we switch over to the app.component.HTML file, we could see the HTML that is associated with the main app component.
Now let's add some HTML. Underneath our H1 we'll type paragraph, "It certainly does!" and save it. Now let's go back to our browser, but first, ensure at the command line that you have ngserveran. And there you go! Our new paragraph element has been added. But what if we wanted to write our HTML inline within the component file itself? Well, let's switch back.
Let's go ahead real quickly and copy this HTML. We will go to our component file, we're going to rename the template URL property to simply template. And right here, we're going to use back ticks. This will allow us to write multi-line HTML. Let's go ahead and paste in the HTML that we had previously, and let's also change our H1 to inline HTML.
Let's save it, we'll go back to the browser. And there we go! Now we can see that instead of the HTML coming from an external template file, the HTML for this component is now coming from the component decorator's template property. So, again, the two ways of defining HTML for a component are inline with the template property, and externally in a separate HTML file using the template URL property.
Released
6/2/2017- How components work
- Defining HTML templates
- Defining CSS
- Interpolation
- NgFor
- NgSwitch
- Class binding and style binding
- Property binding and event binding
- Animation
- Creating routes for navigation
Share this video
Embed this video
Video: Defining HTML templates