动态组件未正确绑定
Dynamic component does not bind properly
在我们的 Angular 2 应用程序中,我们使用来自 Kendo 的 Combobox 组件。该组件被包装到运行时动态创建的组件中。创建代码非常简单:
let factory = this.resolver
.resolveComponentFactory(ComboboxComponent);
nextTo.createComponent(factory);
nextTo
变量表示 Angular 必须在哪里创建组件。
@ViewChild('container', { read: ViewContainerRef })
container: ViewContainerRef;
container
变量表示 HTML 模板中的 div
。
NB :组件是在 ngAfterViewInit
事件期间创建的。创建期间不会抛出任何错误。
Kendo组件正确实例化和初始化,但是当我们在创建后影响数据时,组件似乎不识别绑定,什么也不做。有什么想法吗?
HTML 的组件:
<kendo-combobox [data]="listItems"></kendo-combobox>
打字稿:
@Component({
templateUrl: `combobox.component.html`,
selector: 'combobox',
styleUrls: [
'combobox.component.css'
]
})
export class ComboboxComponent extends FieldComponent {
public listItems: Array<string> = ["X-Small", "Small", "Medium", "Large", "X-Large", "2X-Large"];
}
NB2 : FieldComponent
是一个抽象 class 我们用于所有组件的全局操作。
EDIT1 : 我终于设法找到了问题所在,但我不能说出了什么问题。当我检查 DOM 时,我可以看到隐藏了一个 <div role='combobox'>
,这是包含所有数据的组合框。那么,为什么我显示的第二个组合框没有数据?
我怀疑在这种情况下没有触发组件的变化检测。
createComponent
returns 创建动态组件后 ChangeDetectorRef 的 ComponentRef which has the change detector associated with that component. You can try calling detectChanges()。
我找到了导致这种奇怪行为的原因。由于项目的最初开始,我们使用 Kendo JQuery 作为我们的组件,我们使用 kendo.all.js
。我真的不知道为什么,但似乎 kendo.all.js
干扰了新 Angular 组件的 kendo-combobox
HTML 模板,它注入了一些不自律的 HTML 导致奇怪的行为。
在我们的 Angular 2 应用程序中,我们使用来自 Kendo 的 Combobox 组件。该组件被包装到运行时动态创建的组件中。创建代码非常简单:
let factory = this.resolver
.resolveComponentFactory(ComboboxComponent);
nextTo.createComponent(factory);
nextTo
变量表示 Angular 必须在哪里创建组件。
@ViewChild('container', { read: ViewContainerRef })
container: ViewContainerRef;
container
变量表示 HTML 模板中的 div
。
NB :组件是在 ngAfterViewInit
事件期间创建的。创建期间不会抛出任何错误。
Kendo组件正确实例化和初始化,但是当我们在创建后影响数据时,组件似乎不识别绑定,什么也不做。有什么想法吗?
HTML 的组件:
<kendo-combobox [data]="listItems"></kendo-combobox>
打字稿:
@Component({
templateUrl: `combobox.component.html`,
selector: 'combobox',
styleUrls: [
'combobox.component.css'
]
})
export class ComboboxComponent extends FieldComponent {
public listItems: Array<string> = ["X-Small", "Small", "Medium", "Large", "X-Large", "2X-Large"];
}
NB2 : FieldComponent
是一个抽象 class 我们用于所有组件的全局操作。
EDIT1 : 我终于设法找到了问题所在,但我不能说出了什么问题。当我检查 DOM 时,我可以看到隐藏了一个 <div role='combobox'>
,这是包含所有数据的组合框。那么,为什么我显示的第二个组合框没有数据?
我怀疑在这种情况下没有触发组件的变化检测。
createComponent
returns 创建动态组件后 ChangeDetectorRef 的 ComponentRef which has the change detector associated with that component. You can try calling detectChanges()。
我找到了导致这种奇怪行为的原因。由于项目的最初开始,我们使用 Kendo JQuery 作为我们的组件,我们使用 kendo.all.js
。我真的不知道为什么,但似乎 kendo.all.js
干扰了新 Angular 组件的 kendo-combobox
HTML 模板,它注入了一些不自律的 HTML 导致奇怪的行为。