Angular 2 中的 ViewChildren 和 ContentChildren

原文地址:http://blog.mgechev.com/2016/01/23/angular2-viewchildren-contentchildren-difference-viewproviders/

在这篇文章中,我将解释在Angular 2中view children和content children之间的区别,我们将看看如何从父组件来访问这两种不同的children,除了这些内容,我们也将提到在@Component 装饰器中提供的属性providersviewProviders之间的区别。

你可以在我的github找到这篇文章的源代码,所以让我们开始吧!

组合基元(Composing primitives)

首先,让我们弄清Angular2组件(Component)和指令(Directive)概念之间的关系。组合模式是一个典型的设计模式用来开发用户界面。它使我们能够组成不同的基元,并以相同的方式对待它们。在函数式编程的世界中,我们可以组合函数。 例如:

map ((*2).(+1)) [1, 2, 3]
-- [4,6,8]

上面是Haskell的代码,我们组合函数(*2)(+1),以便后面的列表中每个项目n被共同操作,操作顺序为n -> + 1 -> * 2

UI中的组成

那么,在用户界面,实际上相当类似的,我们可以将各个组件当做函数,这些函数可以被组合在一起,作为结果,我们得到更多复杂的功能。

在上图中,我们有2个元素

  • Directive - 一个独立的持有一些逻辑的元素,但不包含任何结构。
  • Component - 一个元素,它指定了Directive元素,并拥有其他指令实例的列表(这也可能是Component,因为Component继承Direcitve)。

这意味着,使用上述的抽象概念,我们可以构建以下形式的结构:

Angular 2中组件的组合

// ...
@Component({
  selector: 'todo-app',
  providers: [TodoList],
  directives: [TodoCmp, TodoInputCmp],
  template: `
    <section>
      Add todo:
      <todo-input (onTodo)="addTodo($event)"></todo-input>
    </section>
    <section>
      <h4 *ngIf="todos.getAll().length">Todo list</h4>
      <todo *ngFor="var todo of todos.getAll()" [todo]="todo">
      </todo>
    </section>
    <ng-content select="footer"></ng-content>
  `
})
class TodoAppCmp {
  constructor(private todos: TodoList) {}
  addTodo(todo) {
    this.todos.add(todo);
  }
}
// ...

是的,这将是“另一个MV* todo应用”。上面我们定义了一个组件selector是todo-app,它有一些内联模板,定义了一组指令,它或它的任何子组件可以使用。

我们可以以下列方式使用组件:

<todo-app></todo-app>

这基本上是一个XML,因为在<todo-app></todo-app>之间我们可以添加一些内容:

<todo-app>
  <footer>
    Yet another todo app!
  </footer>
</todo-app>

ng-content

让我们先回到todo-app组件的定义,请注意模板的最后一行元素<ng-content select="footer"></ng-content>,ng-content会替换<todo-app></todo-app>之间内容到模板内,select属性的值是一个CSS选择器,这使得我们可以选择我们想要投射的内容,例如在上面的例子中,footer将在所渲染的todo组件的底部被注入。

我们也可以不是用select属性,在这种情况下,我们将投射<todo-app></todo-app>之间的所有内容。

这里的实现很有很多组件,我们在这里并不不需要关心它们是怎么样实现,所以在这里忽略它们,应用的最终结果将是如下:

ViewChildren和ContentChildren

是的,它是那么的简单,现在,我们已经准备好来定义什么是view children和content children的概念。

  • 在组件的模板中定义的内容,它是组件的一部分,被称为view children
  • host元素<opening></closing>标签中的被称为content children

这意味着,在todo-app中的todo-inputtodo是view children,而footer(如果它被定义为Angular 2组件或指令)为content child。

访问 View 和 Content Children

现在到了有趣的部分!让我们看看我们如何能够访问和操作这两种类型的Children!

不同方式访问View Children

Angular 2 在 angular2/core包中提供了下列属性装饰器:@ViewChildren, @ViewChild, @ContentChildren@ContentChild

我们可以通过以下方式:

import {ViewChild, ViewChildren, Component...} from 'angular2/core';

// ...

@Component({
  selector: 'todo-app',
  providers: [TodoList],
  directives: [TodoCmp, TodoInputCmp],
  template: `...`
})
class TodoAppCmp {
  @ViewChild(TodoInputCmp)
  inputComponent: TodoInputCmp
  @ViewChildren(TodoCmp)
  todoComponents: QueryList<TodoCmp>;

  constructor(private todos: TodoList) {}
  ngAfterViewInit() {
    // available here
  }
}

// ...

上面例子显示我们如何使用@ViewChildren@ViewChild,基本上,我们可以装饰一个属性,这样它会来查询视图中的某个元素,在上面例子中,使用@ViewChild查询TodoInputCmp子组件和使用@ViewChildren查询TodoCmp,我们使用不同的装饰器,是因为我们只有一个input,所以我们用@ViewChild来获取它,而我们有多个todo项,所以我们需要使用@ViewChildren

另外要注意的是的inputComponent和todoComponents的属性类型,第一个属性的类型是TodoInputCmp,如果Angular在组件控制器实例中还未发现该子组件或者引用,则它的值为空。另一方面,我们有多个TodoCmp实例,并可以从视图中动态的添加或移除,所以todoComponents属性的类型是QueryList<TodoCmp>,我们可以认为QueryList作为一个观察的集合,一旦项目被添加或删除它可以发出事件。

由于Angular的DOM编译todo-app组件在它的子组件inputComponent实例化和todosComponent实例化之前,所以在todo-app初始化时inputComponenttodoComponents不会被设置,它们的值要在ngAfterViewInit生命周期钩子被触发后才被设置。

访问Content Children

几乎是相同的规则来访问content children,但是,也有一些轻微的差别。为了更好地说明它们,让我们一起来看看它的使用:

@Component({
  selector: 'footer',
  template: '<ng-content></ng-content>'
})
class Footer {}

@Component(...)
class TodoAppCmp {...}

@Component({
  selector: 'app',
  styles: [
    'todo-app { margin-top: 20px; margin-left: 20px; }'
  ],
  template: `
    <content>
      <todo-app>
        <footer>
          <small>Yet another todo app!</small>
        </footer>
      </todo-app>
    </content>
  `,
  directives: [TodoAppCmp, NgModel, Footer]
})
export class AppCmp {}

在上面的代码段,我们定义了两个组件Footer和AppCmp,Footer可视化其host元素标签内的所有内容(<footer>content to be projected</footer>)。

另一方面,AppCmp使用TodoAppCmp的标签来传递Footer,鉴于我们上面的术语,Footer是Content Child,我们可以以下列方式访问:

// ...
@Component(...)
class TodoAppCmp {
  @ContentChild(Footer)
  footer: Footer;
  ngAfterContentInit() {
    // this.footer is now with value set
  }
}
// ...

我们从上面可以看到,View Children和Content Children的区别是装饰器的名字和生命周期不同,为了获取所有的Children,我们使用@ContentChildren(如果只要获取一个,可以使用ContentChild),Children会在ngAfterContentInit之后被设置

viewProviders vs providers

好吧!我们差不多讲完了,最后让我们来看下providers和viewProviders之间的区别,如果你还不熟悉Angular 2的依赖注入,可以看下该文章Angular 2中的依赖注入

让我们来看下TodoAppCmp

class TodoList {
  private todos: Todo[] = [];
  add(todo: Todo) {}
  remove(todo: Todo) {}
  set(todo: Todo, index: number) {}
  get(index: number) {}
  getAll() {}
}

@Component({
  // ...
  viewProviders: [TodoList],
  directives: [TodoCmp, TodoInputCmp],
  // ...
})
class TodoAppCmp {
  constructor(private todos: TodoList) {}
  // ...
}

@Component 我们设置了viewProviders属性,是一个数组,里面有一个元素TodoList服务,TodoList服务保存了所有todo项。

我们在TodoAppCmp构造函数中注入了TodoList服务,但我们也可以在TodoAppCmp视图中使用的其他指令(或组件)中注入该服务,这意味着下列组件可以使用TodoList:

  • TodoList
  • TodoCmp
  • TodoInputCmp

但是,如果我们尝试在footer组件的构造函数中注入该服务,我们会得到以下运行时错误:

EXCEPTION: No provider for TodoList! (Footer -> TodoList)

这意味着在viewProviders声明的只允许组件的模板内的组件使用。

如果我们想让Footer组件使用TodoList服务,可以将TodoList声明在providers属性中。

何时使用viewProviders

为什么要使用viewProviders?如果这些provider无法被content children访问到?假设你现在在开发第三方库,它内部使用一些服务,这些服务是库私有API的一部分,你不想让它们能被外部访问到,如果这些私有的内容注册在providers里用户可以通过content children来访问到这些私有的内容,但是如果你使用viewProviders,该providers将无法从外部访问

转自http://zai.io/topic/detail/news/fd4327d2fe6f801a
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值