角度2具有不同业务逻辑的多个地方的相同组件

时间:2017-06-26 14:49:55

标签: javascript angular typescript generic-programming use-case

对不起问题的长度。我有一些设计问题。

我有一个组件,它将roomView数组作为@Input并在HTML页面中显示它们。

export class RoomView {
"id": string,
"name": string,
"markerIcon": string,
"backgroundColorClass": string
}

室温browser.component.ts

@Component({
    selector: 'room-browser',
    templateUrl: 'room-browser.component.html',
})
export class RoomBrowserComponent {
    @Input() roomsList: RoomView[]: = [];
}

室温browser.component.html

<div *ngFor="let room of roomsList">
    <div class="room.backgroundColorClass">
    {{room.name}}
    <i class="{{room.markerIcon}}"></i>
    </div>

enter image description here

我的通用会议室组件提供roomView到房间浏览器

仿制room.component.ts

@Component({
    selector: 'room',
    templateUrl: 'room.html',
})
export class GenericRoomComponent implements OnInit {

    @Input() source: string;

    private roomView: RoomView[] = [];

    ngOnInit() {
        this.roomView = // i am getting this from backed successfully
        // here I need to decide marker icon and background color class based on some criteria which differs from page to page
        // I have different sections like space, energy, maintenance etc...
        // for space, needs to get space usage for rooms from backend and then decide color
        // for energy, needs to get energy usage and decide the colors
        // for maintenance, needs get devices information of rooms and decide color

    //I want to avoid something like this
    if (this.source === 'space') {
         // get space usage
    } else if (this.source === 'energy') {
         // get space usage
    } else if (this.source === 'maintenance') {
         // get device info and decide color
    }
    }

}

room.html

<room-browser [roomsList]="roomView"></room-browser>

space.html

<room [source]="space"></room>

energy.html

<room [source]="energy"></room>

maintenance.html

<room [source]="maintenance"></room>

我需要根据一些不同页面的标准来决定标记图标和背景颜色类。

我有不同的部分,如空间,能源,维护等......对于空间,需要从后端获取房间的空间使用然后决定颜色,能源需求以获得能源使用并决定颜色和维护需求得到房间的设备信息和决定颜色

那么我如何以及在哪里可以在通用组件中实现这个特定于用例的逻辑呢?

2 个答案:

答案 0 :(得分:0)

我不确定我是否完全了解您的场景,但您可以为GenericRoomComponent为每种颜色添加颜色属性,并通过其他@Input属性将它们传递给子组件。

或者您可以构建一个保留这些值的服务,并让每个子组件读取这些值。

答案 1 :(得分:0)

如果您想在多个模块中使用组件,您需要创建一个&#34;共享&#34;模块并将该组件添加到共享模块的导出中。然后将该共享模块添加到其他模块导入中。