angular - 如何从指令中填充选择选项?
问题描述
这是一个简单的选择:
<select [(ngModel)]="..." name="..." id="..." required ...>
<option *ngFor="let o of options" [ngValue]="o.value">{{o.label}}</option>
</select>
选项初始化如下:
class MyComponent() {
options;
constructor(someService: MyService) {
this.options = someService.getAllOptions();
}
}
到目前为止,一切都很好。一切正常。然而问题是我需要这个选择在不同的位置具有完全相同的选项。所以有很多组件都具有这个options
-Property 并从我的服务中加载它。这是我想避免的大量代码重复。
显然,组件是一个选项,所以我可以只写<mySelect ...>
,但缺点是,我需要通过许多其他变量,例如id
、class
、name
,required
可能还有更多属性。所以我更喜欢指令解决方案,所以我可以编写<select [(ngModel)]="..." name="..." ... myDirective>
并且myDirective
应该根据需要添加选项。我怎样才能做到这一点?
解决方案
在指令中,您可以使用 -Parameter 轻松访问 HTML 元素ElementRef
,因此添加元素选项没有问题。关键是,您需要使用SelectControlValueAccessor
. 通常,一个<option>
-Element 在编译时被 angular 识别,并NgSelectOption
创建一个在构造函数中注册自身的元素。由于您动态创建了该选项元素,因此您需要手动执行此步骤:
@Directive({
selector: '[myDirective]'
})
export class MyDirective {
constructor(someService: MyService,
element: ElementRef<HTMLSelectElement>,
renderer: Renderer2,
@Optional() @Host() select: SelectControlValueAccessor) {
someService.getAllOptions().forEach(co => {
const option = document.createElement('option');
option.text = co.displayName;
option.value = co.id;
element.nativeElement.add(option);
new NgSelectOption(new ElementRef(option), renderer, select);
});
}
}
推荐阅读
- reactjs - UseSelector 返回我未定义
- android - 识别访问 Web 的用户过去访问了本机应用程序?
- node.js - 撇号:parseAggregate:dict 键后的预期冒号
- java - Android 使用 ViewPager 和 TabLayout 包装内容
- c# - 如何设置注释边框的外观
- sql - sql 查询打印表 A 中的 id 和销售额,以查找当年销售额大于去年的行?
- r - 我正在使用 R gamlss 包来适应发行版。我想用数据中的协变量拟合伽马分布
- r - 已安装的包在容器映像中不可用
- c - gcc 为每个 C 程序完成了哪些其他“幕后”工作?
- javascript - 导入场景后无法检索所有网格