[Angular] Advanced DI
In this post, we are going to see how to solve one design pattern challenge.
The challenge is what we a simplest way to find out the children elements which belongs to Animals, which belongs to Materials inside the container component.
<app-animals>
<cat></cat>
<dog></dog>
<rock></rock>
<fox></fox>
<viking></viking>
</app-animals>
As we can see that:
Animals are <cat>, <dog>, <fox>, <viking>.
Material is <rock>.
1. First way we might use is Tamplate Ref:
<cat #item></cat>
<fox #item></fox>
// #item Ref
It will work, but the problem for this solution is that, the container should know what children it has. Also the chance that I might mis-mark the component.
2. We can use 'directive' + {read: ElementRef}:
animal.directive.ts:
import { Directive } from '@angular/core';
@Directive({
// tslint:disable-next-line:directive-selector
selector: '[animal]'
})
export class AnimalDirective {}
<cat animal></cat>
<dog animal></dog>
@ContentChildren(AnimalDirective, {read: ElementRef}) directiveElementsQL: QueryList<ElementRef>;
const directiveElements = this.directiveElementsQL.toArray();
Here without {read: ElementRef}, it won't work. We need it to tell Angular we are actually looking for the host element of the directive. Not direcitve itself.
But still the same problem as Tempalte Ref, we need to mark in the template to tell which component we need.
3. Similar to using directive only, but {read: <interface>}.
We create a Animal interface and the component implements Animal interface.
animal.ts:
export abstract class Animal {
name: string;
abstract speak(): void;
abstract clear(): void;
}
dog.component.ts:
import { Component } from '@angular/core';
import { Animal } from './animal';
@Component({
// tslint:disable-next-line:component-selector
selector: 'dog',
template: `
<div>
<img src="../assets/dog.jpg"/>
<h3>{{saying}}</h3>
</div>
`,
})
// Subclasses Animal
export class DogComponent extends Animal {
name = 'Dog';
saying: string;
speak() {
this.saying = 'Woof';
}
clear() {
this.saying = '';
}
}
Now what we can do is Query by Animal interface in the contianer component:
<cat animal ></cat>
@ContentChildren(AnimalDirective, {read: Animal}) directiveAnimalsQL: QueryList<Animal>;
const directiveAnimals = this.directiveAnimalsQL.toArray();
console.log("directiveAnimals", directiveAnimals);
/*
CatComponent {injector: Injector_, name: "Cat"}
DogComponent {name: "Dog"}
FoxComponent {name: "Fox"}
VikingComponent {name: "Viking"}
*/
4. Recommended: Finally we come to our recommended solution.
Using alias Injection of the component itself.
import { Component } from '@angular/core';
import { Animal } from './animal';
@Component({
// tslint:disable-next-line:component-selector
selector: 'fox',
template: `
<div>
<img src="../assets/fox.jpeg"/>
<h3>{{saying}}</h3>
</div>
`,
providers: [
{ provide: Animal, useExisting: FoxComponent }
]
})
export class FoxComponent implements Animal {
name = 'Fox';
saying: string;
speak() {
this.saying = 'ring-ding-ding-ding-dingedinging';
}
clear() {
this.saying = '';
}
}
For the animals related component, we inject the provider 'useExisting', so it always refer to the same instance. And we use interface Animal as alias.
Now, our container can be really clean:
<cat ></cat>
<dog></dog>
// Any projected component with an Animal "interface" in its injector
@ContentChildren(Animal) animalsQL: QueryList<Animal>;
ngAfterContentInit() {
const animals = this.animalsQL.toArray();
}
[Angular] Advanced DI的更多相关文章
- [Angular 2] DI in Angular 2 - 1
Orgial aritial --> Link The problem with Angular 1 DI: Angular 2 DI: Solve the singletons problem ...
- [Angular] Angular Advanced Features - ng-template , ng-container, ngTemplateOutlet
Previously we have tab-panel template defined like this: <ul class="tab-panel-buttons" ...
- 来自 Thoughtram 的 Angular 2 系列资料
Angular 2 已经正式 Release 了,Thoughtram 已经发布了一系列的文档,对 Angular 2 的各个方面进行深入的阐释和说明. 我计划逐渐将这个系列翻译出来,以便对大家学习 ...
- Angular概念纵览
Conceptual Overview Template(模板): HTML with additional markup (就是增加了新的标记的HTML) Directive(指令): extend ...
- (七)理解angular中的module和injector,即依赖注入
(七)理解angular中的module和injector,即依赖注入 时间:2014-10-10 01:16:54 阅读:63060 评论:1 收藏:0 [点 ...
- angular问题总结与反思
因为工作中实际开发需要,才开始接触angular框架.从当初的比葫芦画瓢,被各种问题.概念折磨摧残,到现在有一定的了解认识,觉得有必要将自己的认识进行简单的总结.不到位的地方还望多多包涵. 1.双向数 ...
- [Angular 2] Understanding @Injectable
In order to resolve a dependency, Angular’s DI uses type annotations. To make sure these types are p ...
- [Angular 2] Factory Provider with dependencies
This lesson discusses when and how to add dependencies, resolved by Angular’s DI, to factory provide ...
- [Angular 2] Factory Provider
In this lesson, we discuss how and when to use factory providers, to enable dependencies that should ...
随机推荐
- [SpringMVC]定义多个前缀映射的问题
转自:https://penciltim.iteye.com/blog/501073 我在web.xml里面定义多个dispatch-servlet的前缀映射,像下面这样 <!-- Servle ...
- JS文件中的中文在网页上显示为乱码解决方法
转自:http://www.pc6.com/infoview/Article_63835.html 如果JS文件中的中文在网页上显示为乱码,不妨采用本文章中的方法来试一试,或许能解决使你很头疼的问题. ...
- 3-4 第三天 Generator生成器
Generator是ES6里面的新增规范,ES6其实就是ES2015.ES5.ES6.ES7这些术语大家上网一查就都明白了.JavaScript是一个范程,就是我们说的JS.ES就是ECMA Scri ...
- (Go)11.九九乘法表示例
//九九乘法表 package main import ( "fmt" ) func chengfa() { ; m < ; m ++ { ; n <= m; n++ ...
- E20170902-hm
devise v. 设计; 想出; 发明; 策划; n. 遗赠; 遗赠的财产; 遗赠的条款; device n. 设备
- centos vi和vim用法
所有的 Unix Like 系统都会内建 vi 文书编辑器,其他的文书编辑器则不一定会存在. 但是目前我们使用比较多的是 vim 编辑器. vim 具有程序编辑的能力,可以主动的以字体颜色辨别语法的正 ...
- spark作业运行过程之--DAGScheduler
DAGScheduler--stage划分和创建以及stage的提交 本篇,我会从一次spark作业的运行为切入点,将spark运行过程中涉及到的各个步骤,包括DAG图的划分,任务集的创建,资源分配, ...
- javaweb 课程设计编码和设计文档
企业办公软件设计文档 1引言 1.1编写目的 OA办公自动化系统详细设计是设计的第三个阶段,这个阶段的主要任务是在OA办公自动化系统概要设计书基础上,对概要设计中产生的功能模块进行过程描述,设计功能模 ...
- Python生成器(yield)
对于调用一个普通的Python函数,一般是从函数的第一行代码开始执行,结束于return语句.异常或者函数所有语句执行完毕.一旦函数将控制权交还给调用者,就意味着全部结束.函数中做的所有工作以及保存在 ...
- lsit集合去重复 顶级表达式
updateList = updateList.Where((x, i) => updateList.FindIndex(z => z.ID == x.ID) == i).ToList() ...