在组件内部使用模板标签

时间:2017-02-26 18:00:58

标签: angular typescript

我编写了一个自定义下拉组件,我想在其中使用template标记来设置输出样式。例如:

<cstm-dropdown [model]="incident.sensor" [options]="sensors" [id]="'id'">            
      <template>
         {{option.name | localName}}
      </template>  
</cstm-dropdown>

这应该显示选项的name属性,并在其上进行一些管道转换。

我的组件是:

import { Component, Input, OnChanges } from '@angular/core';

@Component({
  selector: 'cstm-dropdown',
  template: `
      <select [ngModel]="selectedOption"  (ngModelChange)="onModelChange($event)" >
        <option *ngFor="let option of options" [ngValue]="option">
          <!-- The template should be rendered here -->
        </option>
      </select>
    `
})
export class CustomDropdownComponent implements OnChanges {

  @Input() model: any;

  selectedOption: any;

  @Input() options: any[];

  @Input() id: any;

  @Input() idProperties: any[];

  ngOnChanges() {
    if (!this.identifyByProperty()) {
      this.identifyByProperties();
    }
  }

  onModelChange(event) {
    for (const key of Object.keys(event)) {
      this.model[key] = event[key];
    }
  }

  identifyByProperty(): boolean {
    if (!this.id) {
      return false;
    }

    for (const option of this.options) {
      if (this.model[this.id] === option[this.id]) {
        this.selectedOption = option;
        return true;
      }
    }

    return false;
  }

  identifyByProperties(): boolean {
    // if the array isn't passed
    if (!this.idProperties) {
      return false;
    }
    // if the passed array is empty
    if (!this.idProperties.length) {
      return false;
    }

    for (const option of this.options) {
      if (this.arePropertiesIdentical(option)) {
        this.selectedOption = option;
        return true;
      }
    }

    return false;
  }

  arePropertiesIdentical(option: any): boolean {
    for (const prop of this.idProperties) {
      if (this.model[prop] !== option[prop]) {
        return false;
      }
    }
    return true;
  }

}

我读到我应该使用TemplateRef,但无法修改任何有关如何使用它进行模板化的教程。欢迎任何帮助:)

1 个答案:

答案 0 :(得分:0)

您可以使用 Content Projection ,如下所示

@Component({
  selector: 'cstm-dropdown',
  template: `
      <select [ngModel]="selectedOption"  (ngModelChange)="onModelChange($event)" >
        <option *ngFor="let option of options" [ngValue]="option">
        <ng-content select=".custom-template"> </ng-content>
          <!-- The template should be rendered here -->
        </option>
      </select>
    `
})

您必须在HTML中使用选择器,以便您的内容模板中填充相关模板

<cstm-dropdown [model]="incident.sensor" [options]="sensors" [id]="'id'">            
     <div class="custom-template">
      <template>
         {{option.name | localName}}
      </template>  
     <div>
</cstm-dropdown>