我正在尝试基于HTML选择控件在Angular中创建自定义控件。
在呈现此控件的选项时,如何动态分配将用于“值”和“文本”的属性?
考虑以下行:
<option *ngFor="let x of values" [value]="x.id">{{x.name}}</option>
我的值字段可能不会总是被命名为“ id”,而我的文本字段可能不会总是被命名为“ name”。呈现此控件时,我希望这些控件基于可以在设计时设置的属性。例如:valueField和textField
到目前为止,这是我的组件-一切正常,除了我能够动态设置将哪个属性绑定到项目值以及将哪个属性绑定到名称的能力之外>
import { Component, Input, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
@Component({
selector: 'steve-select',
template: `
<select *ngIf="!readonly" (change)="onChange($event)" [(ngModel)]="selectValue" [disabled]="disabled">
<option *ngFor="let x of values" [value]="x.id">{{x.name}}</option>
</select>
<span *ngIf="readonly">{{readOnlyText}}</span>
`,
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => StevesSelectComponent),
multi: true
}
]
})
export class StevesSelectComponent implements ControlValueAccessor {
@Input()
public readonly: boolean = false;
@Input()
public disabled: boolean = false;
@Input()
public values;
@Input()
public valueField: string
@Input()
public textField: string
@Input()
public readOnlyText: string
private _selectValue: any = '';
private _onTouchedCallback: () => {};
private _onChangeCallback: (_: any) => {};
get selectValue(): any {
return this._selectValue;
}
set selectValue(value: any) {
if (value !== this._selectValue) {
this._selectValue = value;
this._onChangeCallback(value);
}
this._onTouchedCallback();
}
//From ControlValueAccessor interface
writeValue(value: any) {
this._selectValue = value;
}
//From ControlValueAccessor interface
registerOnChange(fn: any) {
this._onChangeCallback = fn;
}
//From ControlValueAccessor interface
registerOnTouched(fn: any) {
this._onTouchedCallback = fn;
}
}
这是我设想使用此控件的方式:
<steve-select name="ddl1" [readonly]="ro" [disabled]="dis" [values]="jobs" [valueField]="id" [textField]="name" [readOnlyText]="request.jobName" [(ngModel)]="request.jobId" (change)="showChanged()"></steve-select>
任何帮助将不胜感激。谢谢!