我有以下代码:
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>
从以上代码中可以看出,我基本上对两个不同的输入-treeNode和sliceTreeNode做相同的事情。我从两个单独的组件中获得了这两个输入。
如何修改代码以获得更好的可重用性?我目前不能仅使用一个函数来代替冗余函数,因为它们返回不同的东西。
此外,我该如何重用HTML代码?
感谢您的帮助。
答案 0 :(得分:1)
您可以编写一个以TreeNode<string>[]
作为参数的方法:
public getSlices(nodes: TreeNode<string>[]) : TreeNode<string>[] {
// operate on nodes variable instead of instance's properties
...
}