无法绑定到' formGroup'因为它不是“形式”的已知属性。
为什么会收到此错误消息?
请参阅我的http://www.ietf.org/rfc/rfc1738.txt了解实时示例。
文件app.module.ts:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { CustomInputComponent } from './custom-input.component';
@NgModule({
imports: [
BrowserModule, ReactiveFormsModule
],
declarations: [
AppComponent, CustomInputComponent
],
providers: [
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
文件main.ts:
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';
platformBrowserDynamic().bootstrapModule(AppModule);
文件app.component.ts:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators, AbstractControl } from '@angular/forms';
@Component({
moduleId: module.id,
selector: 'my-app',
template: `
<h2>Testing Angular 2: custom form input</h2>
<form [formGroup]="form" (ngSubmit)="submit()">
<custom-input [name]="city" [formControl]="city"></custom-input>
</form>
`
})
export class AppComponent implements OnInit {
private form: FormGroup;
private city: AbstractControl;
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.form = this.fb.group({
'city': 'London'
});
this.city = this.form.controls['city'];
}
submit() {
let formValues = this.form.value;
console.log('submit',JSON.stringify(formValues));
}
}
文件custom-input.compontent.ts:
import { Component } from '@angular/core';
import { AbstractControl } from '@angular/forms';
@Component({
moduleId: module.id,
selector: 'custom-input',
template: '<input [name]="name" [id]="name" [formControl]="formControl" type="text">'
})
export class CustomInputComponent {
@Input() name: string;
@Input() formControl: AbstractControl;
constructor() {}
}
答案 0 :(得分:3)
我开始构建一个新的Plunker,因为你似乎没有正确设置。我还修复了代码中的几个小问题
缺少的是,要用作表单控件的自定义元素需要实现ControlValueAccessor