gpt4 book ai didi

angular - Angular 2 嵌套自定义组件中没有 FormGroupDirective 的提供者

转载 作者:行者123 更新时间:2023-12-02 15:18:11 25 4
gpt4 key购买 nike

在 Angular 2 RC.5 中,我找不到上述错误的修复方法:

Unhandled Promise rejection: Template parse errors:
No provider for FormGroupDirective ("p>Custom begin </p>
<p>Host contains {{hostFormGroup.directives.length}} directives</p>
[ERROR ->]<nested></nested>
<p>Custom end </p>
</div>
"): CustomComponent@4:6 ; Zone: <root> ; Task: Promise.then ; Value:

当嵌套在另一个自定义组件中的自定义组件依赖于包含 @Host() hostFormGroup:FormGroupDirective 时发生。

这是一个 plunker显示场景。 AppComponent 显示了包含 CustomComponent 的响应式(Reactive)/模型驱动形式(暂时没有控件,但这在这一点上并不重要),后者又具有一个 NestedComponent。有关错误详细信息,请参阅开发人员控制台。

一级自定义组件可以依赖于托管 FormGroupDirective 或不依赖,这不会影响问题。如果它具有依赖性,则可以正确解析。无论一级组件中是什么,二级自定义组件都不会发生同样的情况。

如果在 AppComponent 中直接使用相同的 NestedComponent,问题就会消失。

我错过了什么?助教

主要部分代码,供引用:

import { Component, Host } from '@angular/core';
import {
REACTIVE_FORM_DIRECTIVES, FormBuilder,
FormGroup, FormGroupDirective
} from '@angular/forms';

///////////////////////
// Nested

@Component({
selector: 'nested',
template: `
Nested begin<br/>
Nested end <br/>
`,
})
class NestedComponent {
constructor(
@Host() private hostFormGroup: FormGroupDirective) {
}
}

///////////////////////
// Custom

@Component({
selector: 'custom',
template: `
Custom begin <br/>
<nested></nested> <br/>
Custom end <br/>
`,
directives: [NestedComponent],
})
class CustomComponent {
constructor(
@Host() private hostFormGroup: FormGroupDirective) {
}
}

///////////////////////
// App

@Component({
selector: 'my-app',
template: `
<h1>Angular 2 - @Host() issue</h1>
<form [formGroup]="mainForm" accept-charset="UTF-8" role="form">
<fieldset>
<custom></custom>
</fieldset>
</form>
`,
directives: [REACTIVE_FORM_DIRECTIVES, CustomComponent],
})
export class AppComponent {
constructor(formBuilder: FormBuilder) {
this.mainForm = formBuilder.group({});
}
}

最佳答案

错误消息为您指明了正确的方向。您需要声明 FormGroupDirective 是一个提供者。即

@Component({
...
providers: [FormGroupDirective]
});

否则,您需要在更高级别声明它,例如在您的模块中,以便您可以在模块范围内使用它。

关于angular - Angular 2 嵌套自定义组件中没有 FormGroupDirective 的提供者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39104592/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com