[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 ...
随机推荐
- tensorflow在windows操作系统上的安装
在电脑上安装PyCharm和Python3,然后把Python3的安装路径写进系统变量里,Python安装完之后, https://bootstrap.pypa.io/get-pip.py,把这页的代 ...
- 【DP悬线法】奶牛浴场
虽然还是悬线法,但是这道题可不能轻易地套模板了,而是要换一种思路,横着扫一遍,竖着扫一遍,时间复杂度依旧是O(n^2),然而空间复杂度有一定的优化 如果用原来的方法,显然时间空间都会炸(如果你想用ma ...
- Django之ORM的增删改查操作流程
总结:ORM的 查.增.删.改 - 查 - client - 有一个展示页面(xxx_show.html) - 这一个页面一输入执行后,get请求向server端发送 - 这个展示页面有添加按钮.删除 ...
- S - New Year Transportation
Problem description New Year is coming in Line World! In this world, there are n cells numbered by i ...
- vue.js $set的使用 数组
[javascript] view plain copy <!DOCTYPE html> <html lang="en"> <head> < ...
- PL/SQL之基础篇
参考文献:<Oracle完全学习手册>第11章 1.PL/SQL概述 PL/SQL(Procedure Language/Structuer Query Language)是Oracle对 ...
- C# 7.0新加特性
以下将是 C# 7.0 中所有计划的语言特性的描述.随着 Visual Studio “15” Preview 4 版本的发布,这些特性中的大部分将活跃起来.现在是时候来展示这些特性,你也告诉借此告诉 ...
- css属性代码大全总结(一)
一 CSS文字属性: color : #999999; /*文字颜色*/ font-family : 宋体,sans-serif; /*文字字体*/ font-size : 9pt; /*文字大小*/ ...
- 安卓代码迁移:ActionBarActivity: cannot be resolved to a type
参考链接:http://stackoverflow.com/questions/18830736/actionbaractivity-cannot-be-resolved-to-a-type in e ...
- php xss 函数
function xss($string) { if (is_array($string)||is_object($string)||is_resource($string)) { return '' ...