Angular 组件未呈现

Angular Component not rendering

我正在使用 ng2-select 组件扩展另一个组件 - 我将其命名为 my-dropdown-field。但是 ng2-select 组件由于某种原因没有呈现。问题似乎不在 ng2 控件中,而是在我创建的包装器控件中。但是,我无法弄清楚是什么原因造成的。也没有抛出任何错误。如果我使用 ng2-select 它自己的工作正常。我创建了一个可重现的 stackblitz。

https://stackblitz.com/edit/ng2-select-angular2

如果你 运行 这个,你会看到没有 ng2-select 控件被渲染。如果您从 app.component.html:

中注释掉以下部分

不起作用

<form [formGroup]="myGroup" (submit)="showForm()">
    <my-dropdown-field 
    name="country"
    [items]="items"
    [selectedItem]="active"
    formControlName="country">
    </my-dropdown-field>
  <button (click)="showForm()">Show</button>
</form>

并从顶部取消注释:

有效

<form [formGroup]="myGroup" (submit)="showForm()">
    <ng-select 
    name="country"
    [(ngModel)]="active"
    [(active)]="active"
    [items]="items"
    formControlName="country">
    </ng-select>
  <button (click)="showForm()">Show</button>
</form>

然后你会发现它工作得很好。

这是原始 ng2-select 组件的 link:

https://github.com/valor-software/ng2-select

我错过了什么?

MyDropdownFieldComponent 应该实现 ControlValueAccessor 如果您希望它与 ngModel 和反应形式一起使用。

[selectedItem] 不应该是数组或更改名称

在 AppComponent 上,在 ngOnInit 而不是构造函数中创建表单

您的代码无效,因为您覆盖了 ng2-select 的 属性 items。 最初它是 setter (https://github.com/valor-software/ng2-select/blob/development/src/select/select.ts#L269) 所以这一行 @Input() items: Array<string> = []; 改变了原来的行为。

在这种情况下的解决方法是为此 属性 使用不同的名称(optionsobjects 等) 这是工作示例 https://stackblitz.com/edit/ng2-select-angular2-tof6ko?file=app/app.component.html