如何在Angular 2中创建更高阶的组件

时间:2016-10-15 15:51:57

标签: angular

高阶组件(HOC)是React社区中常见的模式。如果你不知道什么是HOC,请参见this article

他们在Angular 2中有意义吗? 如何制作HOC? 有什么例子吗?

2 个答案:

答案 0 :(得分:2)

我对类似于HOC的东西也很感兴趣(像Angular 2中那样重新组合)。我最近试图使用Angular结构指令创建一个类似于mapToProps HOC'Recompose for Angular - mapToInputs。我正在寻找更好的方法。

  @Component({
    selector: 'user-list',
    template: `
       <h2>{{status}} users</h2> 
       <div *ngFor="let item of data">{{item}}</div>
    `
  })
  export class UserList {
    @Input() data: Array<any>;
    @Input() status: string;
  }

  @Directive({selector: '[mapInputs]'})
  export class MapInputs {
    component;

    @Input() set mapInputsComponent(component) {
     this.component = component;
    }

    @Input() set mapInputs(fn) {
      this.vc.clear();
      let factory = this.componentFactoryResolver.resolveComponentFactory(this.component);
      let componetRef =  this.vc.createComponent(factory);

      let inputs = fn();
      console.log(inputs);
      Object.entries(inputs).forEach(([key, value]) => {
        componetRef.instance[key] = value;
      });
    }

    constructor(private vc: ViewContainerRef, 
          private componentFactoryResolver: ComponentFactoryResolver) {
    }
  }

  @Component({
    selector: 'my-app',
    template: `
      <div>
        <button (click)="doubledata()">Doubel Data</button>
        <div *mapInputs="filterBy.bind(null, {data:data, status:'active'}); component: component"></div>
        <div *mapInputs="filterBy.bind(null, {data:data, status:'passive'}); component: component"></div>
        <div *mapInputs="filterBy.bind(null,  {data:data, status:'blocked'}); component: component"></div>
      </div>
    `,
  })
  export class App {
    name: string;
    component = UserList;
    data = ['active', 'active', 'passive', 'blocked', 'blocked'];
    filterBy = (context) => {
       return {
          status: context.status,
          data: context.data.filter(el => el ===  context.status);
       };
    }

    doubledata(){
      this.data = this.data.concat(this.data);
    }

    constructor() {
      this.name = `Angular! v${VERSION.full}`
    }
  }

答案 1 :(得分:1)

使用NgComponentOutlet

简单案例

@Component({selector: 'hello-world', template: 'Hello World!'})
class HelloWorld {
}

@Component({
  selector: 'ng-component-outlet-simple-example',
  template: `<ng-container *ngComponentOutlet="myComponent"></ng-container>`
})
class NgTemplateOutletSimpleExample {
  // This field is necessary to expose HelloWorld to the template.
  myComponent= HelloWorld;
}

official documentation中提供了包括提供注入器和内容在内的高级案例