我寫了一個自定義下拉組件,我想在它裏面使用一個template
標籤來設置輸出的樣式。例如:在組件Angular 2中使用模板標籤?
<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
,但不能fimd如何用它做模板的任何教程。任何幫助,歡迎:)
http://stackoverflow.com/questions/39974126/how-to-pass-an-expression-to-a-component-as-an-input-in-angular2 http://stackoverflow.com/questions/39561688/ nested-templates-in-angular-2 – yurzui
@yurzui謝謝:) 。你可以關閉這個問題。 – user3719857