Sunday, April 30, 2023

Angular- HTML Template in Angular Component

html Template in Angular Component

 In Angular Component post, we have seen that a component consists HTML template, component class, and Metadata. In this post we will see the HTML template in detail-

Html template is nothing but regular Html code with some additional Angular syntax to communicate with the component class.

html template

Angular API interprets the HTML template of a component and generates the HTML and renders it. We can declare the HTML template of a component in two ways-

  • Inline Template
  • Linked Template

Inline Template

We can define the inline HTML template of a component using template config in @Component decorator, as shown below-

In can be single line template inside double quotes or single quotes-

1
2
3
4
5
@Component({
  selector: 'app-root',
  template: '<div><p>Inline template in single line</p></div>',
  styleUrls: ['./app.component.css'],
})

It can also be a multi-line template wrapped inside backticks char `.

1
2
3
4
5
6
7
8
@Component({
  selector: 'app-root',
  template: `<div>
    <p>Multi-line template</p>
    <p>Hello World!!</p>
  </div>`,
  styleUrls: ['./app.component.css'],
})

Linked Template

A component can have a separate HTML file to add your HTML template of component. Use the templateUrl parameter to declare the path of the HTML template file, as shown below-

1
2
3
4
5
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})

It is a best practice to have a separate .html file for a template. It will be easy to work with HTML tags and also maintain it.

No comments:

Post a Comment