如何support/utilize angular2 的多个渲染器?

How to support/utilize angular2's multiple renderers?

考虑到 angular2 将支持多个渲染引擎(HTML,通过 NativeScript 和 React Native 原生),开发故事是什么样的?

是否有动态模板切换?还是应该通过子类处理?

// TypeScript ahead

// Base component implementation
class FooComponent {
  public name: string = 'my name';
  public makeFormal () {
    this.name = this.name.toUpperCase();
  }
}

// HTML Component
@Component({
  selector: '<foo></foo>'
  template: `
    <div>{{name}}</div>
    <button (click)="makeFormal()">Make Formal</button>
  `
})
class FooHtmlComponent extends FooComponent {
  constructor(){
    super();
  }
}

// Native Component
@Component({
  selector: '<foo></foo>'
  template: '... [native stuffs here] ...'
})
class FooHtmlComponent extends FooComponent {
  constructor(){
    super();
  }
}

注意:这一切都可能改变,因为 Angular 2 仍然是 alpha。

AngularConnect 2015 上就此进行了几次很好的讨论。

不过,您尤其需要检查 Angular Universal,这是 "Universal"(又名同构)(又名在服务器上启动的应用程序)渲染方法 Angular 2.

对于渲染到 React-Native,还有一个 library growing here 有更多相关信息。

希望对您有所帮助。

(PS: 标记社区 wiki 因为答案太模糊) ;)

  1. 对组件进行子类化是一种方法。

  2. 您可以使用多个视图装饰器导致以下情况:

@Component({selector:'foo', template: `some nativescript template`})
class Foo {}

等同于:

@Component({selector:'foo'`})
@View({
  template: `some nativescript template`
})
class Foo {}

接下来,您将能够为同一组件提供多个视图。

@Component({selector:'foo'})
@View({
  template: `some nativescript template`,
  platform: 'nativescript'
})
@View({
  template: `some dom stuff`,
  platform: 'dom'
})
class Foo {
}

最后,构建步骤将为每个平台创建一个包,并删除所有针对其他平台的代码。相同的技术可用于为组件提供特定于语言的模板。

  1. Angular 2 可以编写具有单个视图的组件,该组件可以 运行 在所有 dom 平台(浏览器、节点、网络工作者)上。

因此您只需执行以下操作:

@Component({selector:'foo', template: `some dom template`})
class Foo {}

当 Angular 2 一年多前开始浮出水面时,这是我最感兴趣的一个特定区域。最初,我更多地是按照 Victor 上面提到的关于为每个目标平台拥有多个 @View 装饰器的思路来思考的。这要么仍在进行中,要么没有记录,要么不再计划(我不确定?)。

然而,随着事情的发展,我开始看到通过使用自定义 Decorators 更清晰的集成潜力。我在这里详细介绍了这个策略:http://angularjs.blogspot.com/2016/03/code-reuse-in-angular-2-native-mobile.html

另外,我在这里证明了这个策略:https://github.com/NathanWalker/angular2-seed-advanced

我期待其他替代方法,但仍然不确定什么是最好的(如果有的话),但到目前为止我喜欢自定义装饰器方法。

Victor 提到的构建步骤将使用正确的 @View 装饰器构建不同版本的应用程序的想法听起来仍然很有帮助,并希望(至少以某种形式)仍然存在Angular 2.0 的路线图。