我现在正在处理一个非常大的项目,我们正在努力使我们的代码尽可能模块化。我们有多个 Angular 应用程序,我们创建了一个单独的通用 UI 组件库和一个 API 套件,其中包含跨这些应用程序使用的通用服务。
但是,在尝试构建需要与服务一起工作的通用组件时,我们遇到了问题。例如,我现在正在开发一个自动完成组件。该组件应该能够从远程源获取数据并根据输入到组件输入字段中的内容过滤结果。
对于一个实例来说,这种实现很容易。我在我的自动完成组件的构造函数中注入了自动完成服务,然后在父组件上提供它。这使我可以在使用服务时灵活地更改服务的实现细节,同时仍然能够创建与定义的接口一起工作的可重用组件。
例如:
我们要定义自动完成组件使用的接口的服务:
@Injectable()
export class AutocompleteService {
public url: string = 'my-api-default';
constructor(http: Http) {}
fetch(): any {
return this.http.get(this.url);
}
}
Run Code Online (Sandbox Code Playgroud)
自动完成组件实现:
@Component({
selector: 'my-autocomplete',
templateUrl: 'my-autocomplete.component.html'
})
export class MyAutocompleteComponent {
constructor(private autocompleteService: AutocompleteService) {}
getData() {
return this.autocompleteService.fetch();
}
...autocomplete logic...
}
Run Code Online (Sandbox Code Playgroud)
现在我可以定义一个实现自动完成服务的熊服务。我可以将熊服务连接到我的自动完成组件,这样我就可以在我的表单中选择熊的种类。
@Injectable()
export class BearService {
public url: string = 'bear-url';
constructor(http: Http){}
fetch() {
return this.http.get(this.url);
}
}
Run Code Online (Sandbox Code Playgroud)
接下来,我定义了使用我的自动完成组件并提供熊服务来获取我的熊种类数据的父级。
@Component({
selector: 'my-form-component',
template: `
<form> …Run Code Online (Sandbox Code Playgroud) 我正在尝试创建一个将调整为所选项目宽度的选择。
这是 jQuery/Javascript 中的实现:下拉列表宽度适合所选项目文本
我遇到的问题是样式总是空的。如果我尝试将 mainSelectElement 设置为 hiddenSelectElement,它几乎消失了。原因是 nativeElement.style.width 是空白的。我将 style 属性记录到控制台,每个属性都是空白的。我们还对 select 应用了全局样式,这些样式也没有出现。
有谁知道为什么我的样式是空白的?这与 shadow DOM 有关系吗?最重要的是,有什么解决方案吗?
import { Component, Input, Output, EventEmitter, forwardRef, ViewChild, ElementRef, Renderer } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
const SELECT_RESIZE_VALUE_ACCESSOR: any = {
provide: NG_VALUE_ACCESSOR,
useClass: forwardRef(() => SamSelectResizableComponent),
multi: true
}
@Component({
selector: 'sam-select-resizable',
template: `
<select #mainSelectElement [ngModel]="selected" (ngModelChange)="updateSelected($event)">
<ng-content></ng-content>
</select>
<select #hiddenSelectElement>
<option >{{selected}}</option>
</select>
`,
providers: [
SELECT_RESIZE_VALUE_ACCESSOR
]
})
export class SamSelectResizableComponent implements ControlValueAccessor …Run Code Online (Sandbox Code Playgroud)