Passing a component as an 'argument' to another component in Angular 2

前端 未结 3 1344
夕颜
夕颜 2020-12-06 01:38

I am new to web development and I have just started building an Angular 2 app. At this point I am trying to create some CRUD components/forms but I find my self duplicating

3条回答
  •  失恋的感觉
    2020-12-06 02:20

    I'm working on reusable component scenario that might be of use to you. In this example it's configurator component that has a basic structure and it's used to configure other components via values object (comes from form.values).

    import {Component, Input, EventEmitter, ViewEncapsulation} from 'angular2/core';
    
    @Component({
      encapsulation: ViewEncapsulation.None,
      selector: 'configurator',
      template: `
        
    ×

    {{ title }}

    ` }) export class ConfiguratorComponent { @Input() title: string; @Input() values: any = {}; @Input() emitter: EventEmitter; public active: boolean = false; set(key: string, value?: any) { this.values[key] = value || !this.values[key]; if (this.emitter) this.emitter.emit(this.values); } }

    I use it in a host component as a sibling of component it configures.

    @Component({
      directives: [
        ConfiguratorComponent,
        ResourceOneComponent,
      ],
      pipes: [...],
      providers: [...],
      template: `
      
    
        
    
      
      
      `
    })
    class HostComponent {
      public configEmitter = EmitterService.get('resource_one');
    }
    

    The resource component could be:

    class ResourceOneComponent extends CRUDComponent {
      public values: { size: 5 };
      private ngOnChanges() {
        if (this.emitter) 
          this.emitter.subscribe(values => {
            // use values from configurator
          });
      }
    }
    

    This is the service I'm using to communicate between sibling components:

    import {Injectable, EventEmitter} from 'angular2/core';
    
    @Injectable()
    export class EmitterService {
      private static _emitters: { [ID: string]: EventEmitter } = {};
      static get(channel: string): EventEmitter {
        if (!this._emitters[channel]) 
          this._emitters[channel] = new EventEmitter();
        return this._emitters[channel];
      }
    }
    

    EDIT: This might be 'overkill' for your use case (: I just saw other answers, both valid for simpler scenarios... I like to keep things separate as much as possible, so each component does one thing. I've been looking into ways to communicate between reusable components and this solution is something that works nicely. Thought it could be useful to share (;

提交回复
热议问题