Reputation: 113
I have the following code:
rightside.component.ts:
import { Component, Input, ChangeDetectionStrategy, ChangeDetectorRef, Output, EventEmitter } from '@angular/core';
import { DataService } from '../../shared/service/data.service';
import { TreeNode } from '../../shared/dto/TreeNode';
import html from './rightside.component.html';
import css from './rightside.component.css';
@Component({
selector: 'rightside-component',
template: html,
providers: [DataService],
styles: [css],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class RightSideComponent {
@Input() treeNode: TreeNode<string>[];
@Input() sliceTreeNode: TreeNode<string>[];
@Output() deselected = new EventEmitter<TreeNode<string>>();
constructor(private cd: ChangeDetectorRef) {}
public getSelections() : TreeNode<string>[] {
if (typeof(this.treeNode) == "undefined" || (this.treeNode) === null) {
return [];
}
return this.treeNode;
}
public getSlices() : TreeNode<string>[] {
if (typeof(this.sliceTreeNode) == "undefined" || (this.sliceTreeNode) === null) {
return [];
}
return this.sliceTreeNode;
}
public deselect(item: TreeNode<string>):void {
this.deselected.emit(item);
}
}
rightside.component.html :
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<ul class="selection-list">
<li *ngFor="let item of getSelections()">
<button class="btn" (click)="deselect(item)" *ngIf="item.selected">
<i class="fa fa-close"> {{ item.displayName }} </i>
</button>
</li>
</ul>
<ul class="selection-list" >
<li *ngFor="let item of getSlices()">
<button class="btn" (click)="deselect(item)" *ngIf="item.selected">
<i class="fa fa-close"> {{ item.displayName }} </i>
</button>
</li>
</ul>
As seen in the above codes, I am basically doing the same things to two different inputs - treeNode and sliceTreeNode. I am getting these two inputs from two separate components.
How can I modify the code to achieve better reusability? I currently cannot use just one function instead of the redundant functions because they return different things.
Also, how can I reuse the HTML code?
Any help is appreciated.
Upvotes: 0
Views: 150
Reputation: 1147
You could write a method that takes a TreeNode<string>[]
as a parameter:
public getSlices(nodes: TreeNode<string>[]) : TreeNode<string>[] {
// operate on nodes variable instead of instance's properties
...
}
Upvotes: 1