首页 > 解决方案 > 如何从指令中填充选择选项?

问题描述

这是一个简单的选择:

<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 ...>,但缺点是,我需要通过许多其他变量,例如idclassnamerequired可能还有更多属性。所以我更喜欢指令解决方案,所以我可以编写<select [(ngModel)]="..." name="..." ... myDirective>并且myDirective应该根据需要添加选项。我怎样才能做到这一点?

标签: angular

解决方案


在指令中,您可以使用 -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); 
        });
    }
}

推荐阅读