我正在研究可能对您有用的可重用组件场景。在本例中,configurator 组件具有基本结构,用于通过values 对象(来自form.values)配置其他组件。
import {Component, Input, EventEmitter, ViewEncapsulation} from 'angular2/core';
@Component({
encapsulation: ViewEncapsulation.None,
selector: 'configurator',
template: `
<div [hidden]="!active">
<span (click)="active = false">×</span>
<h3>{{ title }}</h3>
<form>
<ng-content></ng-content>
</form>
</div>
`
})
export class ConfiguratorComponent {
@Input() title: string;
@Input() values: any = {};
@Input() emitter: EventEmitter<any>;
public active: boolean = false;
set(key: string, value?: any) {
this.values[key] = value || !this.values[key];
if (this.emitter)
this.emitter.emit(this.values);
}
}
我在 host 组件中使用它作为它配置的组件的兄弟。
@Component({
directives: [
ConfiguratorComponent,
ResourceOneComponent,
],
pipes: [...],
providers: [...],
template: `
<configurator title="Resource One" #cfg [values]="one.values" [emitter]="configEmitter">
<label>Size:
<input type="number" min="0" #size [value]="cfg.values.size" (change)="cfg.set('size', size.value)">
</label>
</configurator>
<resource-one #one [emitter]="configEmitter"></resource-one>
`
})
class HostComponent {
public configEmitter = EmitterService.get('resource_one');
}
资源组件可以是:
class ResourceOneComponent extends CRUDComponent {
public values: { size: 5 };
private ngOnChanges() {
if (this.emitter)
this.emitter.subscribe(values => {
// use values from configurator
});
}
}
这是我用来在同级组件之间进行通信的服务:
import {Injectable, EventEmitter} from 'angular2/core';
@Injectable()
export class EmitterService {
private static _emitters: { [ID: string]: EventEmitter<any> } = {};
static get(channel: string): EventEmitter<any> {
if (!this._emitters[channel])
this._emitters[channel] = new EventEmitter();
return this._emitters[channel];
}
}
编辑:对于您的用例来说,这可能是“矫枉过正”(:我刚刚看到其他答案,都适用于更简单的场景......我喜欢尽可能地将事情分开,所以每个组件都做一件事。我一直在研究可重用组件之间进行通信的方法,这个解决方案效果很好。认为分享(;