I am adding form
input fields using component -
engine-add-contact-form.html
<form (ngSubmit)="onSubmit()" [formGroup]="contact_form">
<md-tab-group>
<md-tab label="Form">
<ang-form></ang-form>
</md-tab>
<md-tab label="Email">
<ang-email></ang-email>
</md-tab>
<md-tab label="Message">
<ang-message></ang-message>
</md-tab>
</md-tab-group>
<button md-raised-button type="submit">Publish</button>
ang-form.html
<div class="form-grid form-title">
<md-input-container>
<input formControlName="contact_form_title"
class="form-title-field" mdInput placeholder="Title" value="">
</md-input-container>
</div>
Using same way i added other components (ang-email ang-message
) html.
I added [formGroup]
directive at engine-add-form.ts
export class EngineAddFormComponent{
contact_form: any;
form_value: any;
constructor(){
this.contact_form = new FormGroup({
contact_form_title: new FormControl('', Validators.minLength(2)),
........
........
});
}
onSubmit(){
this.form_value = JSON.stringify(this.contact_form.value);
console.log(this.form_value);
}
}
I get following error -
Error: formControlName must be used with a parent formGroup directive. You'll want to add a formGroup directive and pass it an existing FormGroup instance (you can create one in your class).
I can't understand what is wrong with my code.
Without a parent FormGroup, [formControl]="name" worked earlier because that directive can stand alone, that is, it works without being in a FormGroup. With a parent FormGroup, the name input needs the syntax formControlName=name in order to be associated with the correct FormControl in the class.
You can also create your own custom components (or directives) that can be bound to form controls—if they implement ControlValueAccessor interface. Angular has built-in ControlValueAccessor implementations for <input> , <textarea> , etc, but not for <div> .
FormControlName is used to sync a FormControl in an existing FormGroup to a form control element by name.
You need to pass formGroup (in your case contact_form) to child component which is ang-form
engine-add-contact-form.html(modified)
<form (ngSubmit)="onSubmit()" [formGroup]="contact_form">
<md-tab-group>
<md-tab label="Form">
<ang-form [group]="contact_form"></ang-form>
</md-tab>
<md-tab label="Email">
<ang-email></ang-email>``
</md-tab>
<md-tab label="Message">
<ang-message></ang-message>
</md-tab>
</md-tab-group>
<button md-raised-button type="submit">Publish</button>
ang-form.html(modified)
<div class="form-grid form-title" [formGroup]="group">
<md-input-container>
<input formControlName="contact_form_title"
class="form-title-field" mdInput placeholder="Title" value="">
</md-input-container>
</div>
Add @Input() group: FormGroup; in your ang-form.component.ts
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With