Angular 2 模板约定

Angular 2 template convention

对于我在 Angular 2 中遇到的每个示例,模板位于组件装饰器中。

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

这是正确的约定吗?当模板变得复杂时,我会想象这种语法会变得很麻烦。

我试过使用 templateUrl 而不是 template。但据我了解,Angular 将通过 ajax 加载模板。 (有点相关,但自从我更新到 2.0.0-rc.3 后,templateUrl 似乎不再有效,但也许我做错了什么)。

处理模板的最佳方式是什么?

你可以在rc3中使用templateUrl;请参阅下面的基本组件的模板代码:

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 应作为常规做法使用,以保持组件定义的整洁。

官方 ng2 教程将帮助澄清一些基本问题,它对我有帮助:https://angular.io/docs/ts/latest/tutorial/

来自Angular2 style guide

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

即将推出的离线模板编译器将内联由 templateUrl 链接的模板。也有 Gulp 个任务可用于执行此操作。

官方风格指南

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

可能会建议您将样式和模板隔离到不同的文件中。

但与此同时,如果您要运送一个组件,单个组件文件将使它变得简单和独立。所以这是关于你的要求。如果您希望独立地重用您的组件,那么将模板文件嵌入到组件中的这种方法会胜出。最后,这是您的选择。

希望对您有所帮助。谢谢你。

模板 url 应该用于编写 html 代码,原因有二: 1. 关注点分离:用于项目开发的约定。 2. 轻松调试:在各种 IDE 中,您可以使用 html lint 插件来查找 html.

中的问题

如果您的 html 是一两行,那么您可以直接使用它。