Joe Joe - 2 months ago 22
Javascript Question

Angular 2 template convention

For every example I come across in Angular 2 the template lives in the component decorator.

import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: '<h1>Hello world</h1>'
})
export class AppComponent { }


Is this the correct convention? When templates become complex I would imagine this syntax becomes cumbersome.

I have tried using templateUrl instead of template. But as I understand it Angular will then load the template via ajax. (Slightly related, but since I've updated to 2.0.0-rc.3 templateUrl no longer seems to be working, but maybe I'm doing something wrong).

What is the best way to handle templates?

Answer

You can use templateUrl in rc3; see below the template code for a basic component:

import { Component, OnInit } from '@angular/core';

@Component({
  moduleId: module.id,
  selector: 'app-my-component',
  templateUrl: 'my-component.component.html',
  styleUrls: ['my-component.component.css']
})
export class MyComponentComponent implements OnInit {

  constructor() {}

  ngOnInit() {
  }

}

templateUrl should be used as a normal practice to keep the component definition clean.

The official ng2 tutorial will help clarify some of the base-questions , it helped me : https://angular.io/docs/ts/latest/tutorial/