[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
   @ContentChildren('item') itemRefsQL: QueryList<any>>
   const items = this.itemRefsQL.toArray();

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
   import { Animal } from './animal';
  @ContentChildren(Animal) animalsQL: QueryList<Animal>;

  ngAfterContentInit() {
     const animals = this.animalsQL.toArray();
  }
复制代码

 

 

Talk, Github

posted @   Zhentiw  阅读(285)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2017-04-19 [tmux] Automate your workflow using tmux scripts
2017-04-19 [Javascript] Case insensitive sorting for string arrays
2016-04-19 [AngularJS] Using $parse Service
2016-04-19 [Angular 2] Child Router
点击右上角即可分享
微信分享提示