Angular 2 Components Templates & Styles


Example

Templates are HTML files that may contain logic.

You can specify a template in two ways:

Passing template as a file path

@Component({
  templateUrl: 'hero.component.html',
})

Passing a template as an inline code

@Component({
  template: `<div>My template here</div>`,
})

Templates may contain styles. The styles declared in @Component are different from your application style file, anything applied in the component will be restricted to this scope. For example, say you add:

div { background: red; }

All divs inside the component will be red, but if you have other components, other divs in your HTML they will not be changed at all.

The generated code will look like this:

generated code

You can add styles to a component in two ways:

Passing an array of file paths

@Component({
  styleUrls: ['hero.component.css'],
})

Passing an array of inline codes

styles: [ `div { background: lime; }` ]

You shouldn't use styles with require as it will not work when you build your application to production.