【发布时间】:2020-06-03 17:02:36
【问题描述】:
我正在尝试创建一个 Angular Elements 组件以嵌入到托管网页中,并且我希望我的组件包含一个 Angular 响应式表单。
构建失败并出现错误:“无法绑定到 'formGroup',因为它不是 'form' 的已知属性。”
谁能指出我做错了什么?
编辑:这是在最新版本的 Angular CLI 上运行的 Angular 9 和 TypeScript 3.7。 Stackblitz:https://stackblitz.com/edit/angular-57wq1s
编辑 2:更新后的 Stackblitz 代码不再引发编译时错误,但控件未完成渲染。提交按钮不呈现。如果我从密码输入中删除“formControlName”指令,组件确实会完全呈现。
编辑 3:StackBlitz 似乎现在可以工作了,但是如果我下载到我的计算机,npm install 和 ng serve,我会遇到问题,它呈现文本框而不是按钮。
Index.html
<!doctype html>
<html lang="en">
<body>
<app-password-reset></app-password-reset>
</body>
</html>
app.module.ts
@NgModule({
declarations: [],
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule
],
entryComponents: [PasswordResetComponent],
providers: [],
})
export class AppModule {
constructor(injector: Injector) {
const passwordResetElement = createCustomElement(PasswordResetComponent, {injector});
customElements.define('app-password-reset', passwordResetElement);
}
ngDoBootstrap(): void { }
}
密码重置.component.ts
@Component({
template: `
<form [formGroup]="resetForm" (ngSubmit)="formSubmit($event)">
<input type="password" formControlName="password">
<button type="submit">Reset Password</button>
</form>`
})
export class PasswordResetComponent {
constructor(private fb: FormBuilder) { }
resetForm = this.fb.group({
password: [null, Validators.required],
});
formSubmit(event: Event) {
alert('it works');
}
}
【问题讨论】:
-
我觉得你还需要导入FormsModule
-
好的,我将它添加到我的 app.module.ts 中,但我仍然遇到同样的错误。我将更新我的原始代码示例。
-
你能在stackblitz.com创建这个项目吗?
-
我将它放入 Stackblitz,但我不确定它是否与 Angular Elements 兼容。它给了我一个不同的错误...stackblitz.com/edit/angular-fsyral
-
@SatishPai -- 忘记标记你