This article is about Angular 5 template and styles and it will guide you over how templates and style works in Angular 5.
We already learned how to install angular 5 and how Angular 5 components work in our previous articles.
Angular 5 provides a powerful HTML based template to interact with the component class and render the outputs on user’s browser.
Also, it provide a variety of preprocessors for CSS such an SCSS, Sass and Stylus.
Let’s take an example of Angular 5 template and styles and continue to seeing an example what we’ve set up in our last article.
Defining a Angular 5 Template
If you open a home component file, you will able to see the template source over there.
/src/app/home/home.component.ts
@Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.scss'] })
templateUrl helps us to specify the source URL of HTML template that is going to associate with this home component.
Also, you can specify the template in the @Component decorator like this:
@Component({ selector: 'app-home', template: ` <p>This is my inline template HTML!</p> `, styleUrls: ['./home.component.scss'] })
Or you can directly write your HTML in home.component.html file by specifying the right templateUrl.
<p>This is my inline template HTML!</p>
Defining a Angular 5 Styles
Same as HTML template, styleUrls will be used to specify the source CSS url for the styling purpose of a HTML template.
Here, you can specify the CSS inline under styles array same as template.
@Component({ selector: 'app-home', templateUrl: './home.component.html', styles: [` p { font-weight: bold; } div { color: gray; } `] })
I personally recommend to use source URL instead of inline, that will help you to make the code neat and clean, see:
Specify the source CSS URL as styleUrls.
/src/app/home/home.component.ts
@Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.scss'] })
And you can define the styles in CSS file.
/src/app/home/home.component.scss
p { font-weight: bold; } div { color: gray; }
That’s it, now you can specify your template and styles to start giving an awesome user experience in your Angular 5 app.
I hope, you understand the basics of Angular 5 template and styles.
Leave a Reply