我有以下代码:
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和slice TreeNode。我从两个独立的组件中获取这两个输入。
如何修改代码以实现更好的可重用性?我目前不能只使用一个函数而不是冗余函数,因为它们会返回不同的东西。
另外,我如何重用HTML代码?
任何帮助表示赞赏。
您可以编写一个以TreeNode<string>[]
作为参数的方法:
public getSlices(nodes: TreeNode<string>[]) : TreeNode<string>[] {
// operate on nodes variable instead of instance's properties
...
}