简体   繁体   English

重用角度和HTML冗余功能

[英]Reusing redundant functions angular and html

I have the following code: 我有以下代码:

rightside.component.ts: 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 : 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. 如上面的代码所示,我基本上对两个不同的输入-treeNode和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? 另外,如何重用HTML代码?

Any help is appreciated. 任何帮助表示赞赏。

您可以编写一个将TreeNode<string>[]作为参数的方法:

public getSlices(nodes: TreeNode<string>[]) : TreeNode<string>[] { // operate on nodes variable instead of instance's properties ... }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM