将组件转换为指令

converting component to directive

我有以下指令(过去是一个组件)

@Component({
  selector: '[passport-detailed-cell]',
  templateUrl: './passport-detailed-cell.component.html',
  styleUrls: ['../passport-cell.component.scss']
})
export class PassportDetailedCell {
  @Input()
  public label: LabelTranlations;

  @Input()
  public dataString: String;

  @Input()
  public language: PassportLanguage;

  @Input()
  public labelPosition: LabelPosition = LabelPosition.LEFT;

  @Input()
  public fontsize: number;

  public LabelPositions = LabelPosition;

  constructor() {}
}

export enum LabelPosition {
  LEFT = 'LEFT',
  RIGHT = 'RIGHT',
  CENTER = 'CENTER'
}

目前有以下HTML

<dt class="cell-content label" [ngClass] = "{
      'left': labelPosition === LabelPositions.LEFT,
        'right': labelPosition === LabelPositions.RIGHT,
        'center': labelPosition === LabelPositions.CENTER }" *ngIf="!!label">
  {{label[language]}}
</dt>
<dd class="data" [ngStyle]="{ 'font-size' : fontsize + 'px' }">
  {{dataString}}
</dd>

正如您从 @Component 定义中看到的那样,它有一个 stylesheet 这很重要,因为它包含用于网格布局的 css。

然而,我的目标是“删除”生成的 HTML,而是使用指令 css

设置“宿主元素”的样式

这方面的一个例子是:

  <dt passport-detailed-cell class="firstname" [labelPosition]="LabelPositions.LEFT" [language]="language">
    {{labels.firstname}}
  </dt>

这可能吗?

为指令尝试这种代码。

import { Directive } from '@angular/core';

export enum LabelPosition {
  LEFT = 'LEFT',
  RIGHT = 'RIGHT',
  CENTER = 'CENTER'
}

@Directive({
  selector: '[appPassportDetailedCell]'
})
export class PassportDetailedCellDirective {

  @Input()
  public label: LabelTranlations;

  @Input()
  public dataString: String;

  @Input()
  public language: PassportLanguage;

  @Input()
  public labelPosition: LabelPosition = LabelPosition.LEFT;

  @Input()
  public fontsize: number;

  constructor(el: ElementRef) {
    switch(this.labelPosition) {
      case LabelPosition.LEFT: 
      el.nativeElement.classList.add("left")
      break;
      case LabelPosition.CENTER: 
      el.nativeElement.classList.add("center")
      break;
      case LabelPosition.RIGHT: 
      el.nativeElement.classList.add("right")
      break;
    }
  }

}