通过注释值创建角度分量?

时间:2019-03-10 23:37:09

标签: angular

当我下面有两个班级


@Component({
  selector: 'app-image-component'
})
export class ImageComponent implements OnInit, OnDestroy {
...
}


@Component({
  selector: 'app-text-component'
})
export class TextComponent implements OnInit, OnDestroy {
...
}

现在我应该按顺序动态创建这些组件。

借助ComponentFactoryResolver

并不难

export class DynamicDrawer {
  let componentListToDraw = ['text', 'text','image', 'text', 'image'];


  constructor(private resolver: ComponentFactoryResolver) {
  }

  drawAll(){
    for(let type of componentListToDraw){
      let factory;
      switch(type){
        case 'image'
          factory = this.resolver.resolveComponentFactory(ImageComponent);
          break;
        case 'text'
          factory = this.resolver.resolveComponentFactory(TextComponent);
          break;
      }

      if(factory){
        let created = this.container.createComponent(factory).instance;
        // now can do some thing for the created component......
      }

    }
  }

这很好,但有一点不是很好,那就是如果组件类型增加DynamicDrawer每次都需要更改。

当我使用Java Spring时,可以通过一些注释实例化一个组件。如果可能的话,这将是对代码的极大改进。

我想象的是


@Component({
  selector: 'app-image-component'
})
@TypeFor('image')  // <--- give some decorator that specify type
                   // refactoring safe, immutable value for the class
export class ImageComponent implements OnInit, OnDestroy {
...
}


@Component({
  selector: 'app-text-component'
})
@TypeFor('text')
export class TextComponent implements OnInit, OnDestroy {
...
}

然后由装饰器获得组件工厂。


export class DynamicDrawer {
  let componentListToDraw = ['text', 'text','image', 'text', 'image'];


  constructor(private resolver: ComponentFactoryResolver) {
  }

  drawAll(){
    for(let type of componentListToDraw){
      // resolve factory by decorator specification.
      factory = this.resolver.resolveComponentFactoryByDecorator(new TypeFor(type);
    }
  }

有什么办法吗?

1 个答案:

答案 0 :(得分:0)

据我所知,我不知道您是否可以通过注释实例化组件。

一种通过查看角度https://angular.io/guide/dynamic-component-loader的文档而想到的方法

您可以将组件封装在一个类中

import { Type } from '@angular/core';

export class DynamicItem {
    constructor(public component: Type<any>) { }
}

然后,您可以在迭代时执行类似的操作

export class DynamicDrawer {
    const dynamicItems = [
        new DynamicItem(MyComponent01),
        new DynamicItem(MyComponent02),
        new DynamicItem(MyComponent03),
        new DynamicItem(MyComponent04),
    ];

    constructor(private resolver: ComponentFactoryResolver) { }

    drawAll() {
        for (let dynamicItem of dynamicItems) {
            let componentFactory = this.componentFactoryResolver.resolveComponentFactory(dynamicItem.component);
            let created = this.container.createComponent(componentFactory).instance;
        }
    }
}