Learnitweb

Inline template in Angular

In this article, we’ll see how to define an inline template associated with a component.

A component is always associated with a component. We usually keep the code of template in an external file and associate that component with templateUrl property of the @Component decorator, like in the following piece of code:

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

If the template is very simple then we can also define template in the component file itself. Inline template is defined using the template property of @Component decorator.

@Component({
  selector: 'app-root',
  template: '<h1>App component works!</h1>',
  styleUrls: ['./app.component.css']
})

Multiline inline template in Angular

It is possible that the template may span multiple lines. In such case, we can’t use single quote (‘) or double quote (“).

If the template spans multiple lines, we can use backtics (`) instead of single quote (‘).

@Component({
  selector: 'app-root',
  template: `<h1>App component works!</h1>
	     <p>This is a multiline inline template.</p>`,
  styleUrls: ['./app.component.css']
})

When to use inline template

Inline template can be used when the template is simple and is of single line or spans few lines. Inline template is preferred when the template is simple.