简体   繁体   中英

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?

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/

From the Angular2 style guide

| Do extract templates and styles into a separate file, when more than 3 lines.

The upcoming offline template compiler will inline templates linked by templateUrl . There are also Gulp tasks available to do this already.

The official style guide

https://angular.io/styleguide#!#05-04

may suggest you to isolate styles and templates into different files.

But at the same time if you are shipping a component the single component file will make it easy and independent. So it is about your requirement. If you want your component to be reused independently this approach where embedding the template file into the component would win. And in the end it's your choice.

Hope this help you. Thank you.

Template url should be used for writing html code because of two reasons: 1. Seperation of concerns : A convention used for project development. 2. Easy debugging: in various IDE's you can use html lint plugins so as to find issue in html.

If your html is of one or two line then you can use it inline.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM