I would like to create a form and use a new, custom component for its controls. So I created a new component and included it into the parent form. But although the parent form has a formGroup, Angular complains that it does not.
The 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).
The parent form has:
<form [formGroup]="learningObjectForm" (ngSubmit)="onSubmit()" novalidate>
<div>
<button type="submit"
[disabled]="learningObjectForm.pristine">Save</button>
</div>
<ava-form-control [label]="'Resource'"></ava-form-control>
</form>
And in the .ts:
constructor(private fb: FormBuilder) {
this.createForm();
}
createForm() {
this.learningObjectForm = this.fb.group({
text: '',
});
}
In the custom component I have
import { Component, Input, OnInit } from '#angular/core';
#Component({
selector: 'ava-form-control',
template: ` <div>
<label>{{label}} :</label>
<input formControlName="{{name}}">
</div>
`
})
export class FormControlComponent implements OnInit {
#Input() label: string;
#Input() name: string;
constructor() {}
ngOnInit() {
if (this.name === undefined) {
// turns 'The Label' into 'theLabel'
this.name = this.label[0].toLowerCase().concat(this.label.slice(1));
this.name = this.name.split(' ').join('');
console.log(this.label, this.name);
}
}
}
You should also be passing the formGroup instance along with control name to your custom component. And then create a form control under that formGroup in custom component. Your custom component will create the control virtually under the same formGroup that you have provided.
<form [formGroup]="learningObjectForm" (ngSubmit)="onSubmit()" novalidate>
<div>
<button type="submit"
[disabled]="learningObjectForm.pristine">Save</button>
</div>
<ava-form-control [label]="'Resource'" [formGroup]="learningObjectForm" [controlName]="'mycontrol'"></ava-form-control>
</form>
custom.component.ts
import { Component, Input, OnInit } from '#angular/core';
#Component({
selector: 'ava-form-control',
template: ` <div>
<label>{{label}} :</label>
<input [formControl]="formGroup.controls[controlName]>
</div>
`
})
export class FormControlComponent implements OnInit {
#Input() label: string;
#Input() formGroup: FormGroup;
#Input() controlName: string;
constructor() {}
ngOnInit() {
let control: FormControl = new FormControl('', Validators.required);
this.formGroup.addControl(this.controlName, control);
}
}
With this your parent component can access all the form controls defined within their respective custom components.
I played around with the accepted answer for a long time, and never had any luck.
I had much better results implementing the ControlValueAccessor interface as shown here:
https://alligator.io/angular/custom-form-control/
It's actually pretty simple, I also rigged up an Example StackBlitz
Related
I'm trying to get the value of an input field in my first ever Angular form, but it is always undefined, and I can't figure out why. I'm importing FormsModule correctly, and I can reference the form object fine, so I must be missing something obvious.
My components HTML
<form #searchValue='ngForm' class="" (ngSubmit)='submitSearch(searchValue)'>
<div>
<input type="text" name="q" placeholder="search">
</div>
</form>
And my components ts method (Shortened)
import { Component, OnInit } from '#angular/core';
import { FormsModule } from '#angular/forms';
#Component({
selector: 'google-search',
templateUrl: './google.component.html',
styleUrls: ['./google.component.css']
})
export class GoogleComponent implements OnInit {
constructor() { }
ngOnInit() {
}
submitSearch(formData) {
console.log(this.searching);
console.log(formData.value.q);
}
}
Any ideas to why this is?
You need to mark the input with ngModel so angular will know that this is one of form's controls:
<input type="text" ngModel name="q" placeholder="search">
Or you can define the variable first in your component, and then bind the input to it via [(ngModel)] directive:
export class GoogleComponent implements OnInit {
q: string;
submitSearch() {
console.log(this.q);
}
}
<form class="" (ngSubmit)='submitSearch()'>
<div>
<input type="text" name="q" [(ngModel)]="q" placeholder="search">
</div>
</form>
One way binding (just [ngModel]="q") could be enough if you just want to read the value from input.
Some like this should work..
Maybe you want to read about model binding and forms.
html component
<form #searchValue='ngForm' class="some-css-class" (ngSubmit)='submitSearch()'>
<div>
<input type="text" name="q" [(ngModel)]="searchValue" placeholder="search">
<input type="submit" name="btn" placeholder="Submit">
</div>
</form>
In component.ts
import { Component, OnInit } from '#angular/core';
import { FormsModule } from '#angular/forms';
#Component({
selector: 'google-search',
templateUrl: './google.component.html',
styleUrls: ['./google.component.css']
})
export class GoogleComponent implements OnInit {
searchValue: string = '';
constructor() { }
ngOnInit() { }
submitSearch() {
console.log(this.searchValue);
}
}
This is the Parent HTML
<parent-component>
<child></child>
<button type="submit" [disabled]="!childForm.valid">
</parent-component>
This is Child HTML
<child>
<form #childform=ngform>
<input required type="text">
</form>
</child>
I need to access the childform status in the parent component
Child template:
<form #childform=ngForm>
<input required type="text">
</form>
Child component:
export class ChildComponent implements OnInit {
#Output() validityChange = new EventEmitter<boolean>();
#ViewChild('childform') form: NgForm;
private validStatus: boolean;
ngOnInit() {
if (!this.form) return;
this.form.valueChanges
.subscribe(_ => {
if(this.validStatus !== this.form.valid) {
this.validStatus = this.form.valid;
this.validityChange.emit(this.form.valid);
});
}
}
Parent template:
<child (validityChange)="childFormValid = $event"></child>
<button type="submit" [disabled]="!childFormValid">
Parent component:
export class ChildComponent implements OnInit {
private childFormValid: boolean;
...
}
Probably you could do it using #ViewChild:
Child component template file:
<form #form="ngForm">
<input type="text" ngModel required name="input">
</form>
and use #ViewChild in child component TS file like this:
#ViewChild('form') form: NgForm;
Parent component template file:
<button type="submit" *ngIf="childForm" [disabled]="!childForm.valid">Submit</button>
and in your parent component TS file reference to child component as well:
export class ParentComponent implements AfterViewInit {
#ViewChild('child') child: ChildComponent;
public childForm;
ngAfterViewInit(): void {
this.childForm = this.child.form.form;
}
}
Use an output
<child (myOutput)="myFunction($event)"></child>
In your parent component :
myFunction(event: Event) {
console.log(event); // hello world
}
In your child component
import { Output, EventEmitter } from '#angular/core';
// ...
#Output() myOutput: new EventEmitter();
doSomething() {
thisMyOutput.emit('hello world');
}
Child Component
export class ChildparentComponent implements OnInit {
#Output() toParent = new EventEmitter<string>();
constructor() { }
onChange(value:string){
this.toParent.emit(value);
}
In Child Html
<app-childparent (toParent)="childValue = $event"></app-childparent>
In Parent
Access this child value in parent template like {{childValue}}
A working example of the Same
https://rahulrsingh09.github.io/AngularConcepts/#/inout
Its Backend Code
https://github.com/rahulrsingh09/AngularConcepts/blob/master/src/app/parentchild/parentchild.component.html
I'm trying achieve a nested form with validation in Angular 2, I've seen posts and followed the documentation but I'm really struggling, hope you can point me in the right direction.
What I am trying to achieve is having a validated form with multiple children components. These children components are a bit complex, some of them have more children components, but for the sake of the question I think we can attack the problem having a parent and a children.
What am I trying to accomplish
Having a form that works like this:
<div [formGroup]="userForm" novalidate>
<div>
<label>User Id</label>
<input formControlName="userId">
</div>
<div>
<label>Dummy</label>
<input formControlName="dummyInput">
</div>
</div>
This requires having a class like this:
private userForm: FormGroup;
constructor(private fb: FormBuilder){
this.createForm();
}
private createForm(): void{
this.userForm = this.fb.group({
userId: ["", Validators.required],
dummyInput: "", Validators.required]
});
}
This works as expected, but now I want to decouple the code, and put the "dummyInput" functionality in a separate, different component. This is where I get lost. This is what I tried, I think I'm not far from getting the answer, but I'm really out of ideas, I'm fairly new to the scene:
parent.component.html
<div [formGroup]="userForm" novalidate>
<div>
<label>User Id</label>
<input formControlName="userId">
</div>
<div>
<dummy></dummy>
</div>
</div>
parent.component.ts
private createForm(): void{
this.userForm = this.fb.group({
userId: ["", Validators.required],
dummy: this.fb.group({
dummyInput: ["", Validators.required]
})
});
children.component.html
<div [formGroup]="dummyGroup">
<label>Dummy Input: </label>
<input formControlName="dummyInput">
</div>
children.component.ts
private dummyGroup: FormGroup;
I know something is not right with the code, but I'm really in a roadblock. Any help would be aprreciated.
Thanks.
you can add an Input in your children component to pass the FormGroup to it.and use FormGroupName to pass the name of your FormGroup :)
children.component.ts
#Input('group');
private dummyGroup: FormGroup;
parent.component.html
<div [formGroup]="userForm" novalidate>
<div>
<label>User Id</label>
<input formControlName="userId">
</div>
<div formGroupName="dummy">
<dummy [group]="userForm.controls['dummy']"></dummy>
</div>
</div>
Not going to lie, don't know how I didn't find this post earlier.
Angular 2: Form containing child component
The solution is to bind the children component to the same formGroup, by passing the formGroup from the parent to the children as an Input.
If anyone shares a piece of code to solve the problem in other way, I'll gladly accept it.
The main idea is that you have to treat the formGroup and formControls as variables, mainly javascript objects and arrays.
So I'll put some code in to make my point. The code below is somewhat like what you have. The form is constructed dynamically, just that it is split into sections, each section containing its share of fields and labels.
The HTML is backed up by typescript classes. Those are not here as they do not have much special. Just the FormSchemaUI, FormSectionUI and FormFieldUI are important.
Treat each piece of code as its own file.
Also please take note that formSchema: FormSchema is a JSON object that I receive from a service. Any properties of the UI classes that you do not see defined are inherited from their base Data clases. Those are not presented here.
The hierarchy is: FormSchema contains multiple sections. A section contains multiple fields.
<form (ngSubmit)="onSubmit()" #ciRegisterForm="ngForm" [formGroup]="formSchemaUI.MainFormGroup">
<button kendoButton (click)="onSubmit(ciRegisterForm)" [disabled]="!canSubmit()"> Register {{registerPageName}} </button>
<br /><br />
<app-ci-register-section *ngFor="let sectionUI of formSchemaUI.SectionsUI" [sectionUI]="sectionUI">
</app-ci-register-section>
<button kendoButton (click)="onSubmit(ciRegisterForm)" [disabled]="!canSubmit()"> Register {{registerPageName}} </button>
</form>
=============================================
<div class="row" [formGroup]="sectionUI.MainFormGroup">
<div class="col-md-12 col-lg-12" [formGroupName]="sectionUI.SectionDisplayId">
<fieldset class="section-border">
<legend class="section-border">{{sectionUI.Title}}</legend>
<ng-container *ngFor='let fieldUI of sectionUI.FieldsUI; let i=index; let even = even;'>
<div class="row" *ngIf="even">
<ng-container>
<div class="col-md-6 col-lg-6" app-ci-field-label-tuple [fieldUI]="fieldUI">
</div>
</ng-container>
<ng-container *ngIf="sectionUI.Fields[i+1]">
<div class="col-md-6 col-lg-6" app-ci-field-label-tuple [fieldUI]="sectionUI.FieldsUI[i+1]">
</div>
</ng-container>
</div>
</ng-container>
</fieldset>
</div>
</div>
=============================================
{{fieldUI.Label}}
=============================================
<ng-container>
<div class="row">
<div class="col-md-4 col-lg-4 text-right">
<label for="{{fieldUI.FieldDisplayId}}"> {{fieldUI.Label}} </label>
</div>
<div class="col-md-8 col-lg-8">
<div app-ci-field-edit [fieldUI]="fieldUI" ></div>
</div>
</div>
</ng-container>
=============================================
<ng-container [formGroup]="fieldUI.ParentSectionFormGroup">
<ng-container *ngIf="fieldUI.isEnabled">
<ng-container [ngSwitch]="fieldUI.ColumnType">
<input *ngSwitchCase="'HIDDEN'" type="hidden" id="{{fieldUI.FieldDisplayId}}" [value]="fieldUI.Value" />
<ci-field-textbox *ngSwitchDefault
[fieldUI]="fieldUI"
(valueChange)="onValueChange($event)"
class="fullWidth" style="width:100%">
</ci-field-textbox>
</ng-container>
</ng-container>
</ng-container>
=============================================
export class FormSchemaUI extends FormSchema {
SectionsUI: Array<FormSectionUI>;
MainFormGroup: FormGroup;
static fromFormSchemaData(formSchema: FormSchema): FormSchemaUI {
let formSchemaUI = new FormSchemaUI(formSchema);
formSchemaUI.SectionsUI = new Array<FormSectionUI>();
formSchemaUI.Sections.forEach(section => {
let formSectionUI = FormSectionUI.fromFormSectionData(section);
formSchemaUI.SectionsUI.push(formSectionUI);
});
formSchemaUI.MainFormGroup = FormSchemaUI.buildMainFormGroup(formSchemaUI);
return formSchemaUI;
}
static buildMainFormGroup(formSchemaUI: FormSchemaUI): FormGroup {
let obj = {};
formSchemaUI.SectionsUI.forEach(sectionUI => {
obj[sectionUI.SectionDisplayId] = sectionUI.SectionFormGroup;
});
let sectionFormGroup = new FormGroup(obj);
return sectionFormGroup;
}
}
=============================================
export class FormSectionUI extends FormSection {
constructor(formSection: FormSection) {
this.SectionDisplayId = 'section' + this.SectionId.toString();
}
SectionDisplayId: string;
FieldsUI: Array<FormFieldUI>;
HiddenFieldsUI: Array<FormFieldUI>;
SectionFormGroup: FormGroup;
MainFormGroup: FormGroup;
ParentFormSchemaUI: FormSchemaUI;
static fromFormSectionData(formSection: FormSection): FormSectionUI {
let formSectionUI = new FormSectionUI(formSection);
formSectionUI.FieldsUI = new Array<FormFieldUI>();
formSectionUI.HiddenFieldsUI = new Array<FormFieldUI>();
formSectionUI.Fields.forEach(field => {
let fieldUI = FormFieldUI.fromFormFieldData(field);
if (fieldUI.ColumnType != 'HIDDEN')
formSectionUI.FieldsUI.push(fieldUI);
else formSectionUI.HiddenFieldsUI.push(fieldUI);
});
formSectionUI.SectionFormGroup = FormSectionUI.buildFormSectionFormGroup(formSectionUI);
return formSectionUI;
}
static buildFormSectionFormGroup(formSectionUI: FormSectionUI): FormGroup {
let obj = {};
formSectionUI.FieldsUI.forEach(fieldUI => {
obj[fieldUI.FieldDisplayId] = fieldUI.FieldFormControl;
});
let sectionFormGroup = new FormGroup(obj);
return sectionFormGroup;
}
}
=============================================
export class FormFieldUI extends FormField {
constructor(formField: FormField) {
super();
this.FieldDisplayId = 'field' + this.FieldId.toString();
this.ListItems = new Array<SelectListItem>();
}
public FieldDisplayId: string;
public FieldFormControl: FormControl;
public ParentSectionFormGroup: FormGroup;
public MainFormGroup: FormGroup;
public ParentFormSectionUI: FormSectionUI;
public ValueChange: EventEmitter<any> = new EventEmitter<any>();
static buildFormControl(formFieldUI:FormFieldUI): FormControl {
let nullValidator = Validators.nullValidator;
let fieldKey: string = formFieldUI.FieldDisplayId;
let fieldValue: any;
switch (formFieldUI.ColumnType) {
default:
fieldValue = formFieldUI.Value;
break;
}
let isDisabled = !formFieldUI.IsEnabled;
let validatorsArray: ValidatorFn[] = new Array<ValidatorFn>();
let asyncValidatorsArray: AsyncValidatorFn[] = new Array<AsyncValidatorFn>();
let formControl = new FormControl({ value: fieldValue, disabled: isDisabled }, validatorsArray, asyncValidatorsArray);
return formControl;
}
}
To get a reference to the parent form simply use this (maybe not available in Angular 2. I've tested it with Angular 6):
TS
import {
FormGroup,
ControlContainer,
FormGroupDirective,
} from "#angular/forms";
#Component({
selector: "app-leveltwo",
templateUrl: "./leveltwo.component.html",
styleUrls: ["./leveltwo.component.sass"],
viewProviders: [
{
provide: ControlContainer,
useExisting: FormGroupDirective
}
]
})
export class NestedLevelComponent implements OnInit {
//form: FormGroup;
constructor(private parent: FormGroupDirective) {
//this.form = form;
}
}
HTML
<input type="text" formControlName="test" />
import { Directive } from '#angular/core';
import { ControlContainer, NgForm } from '../../../node_modules/#angular/forms';
#Directive({
selector: '[ParentProvider]',
providers: [
{
provide: ControlContainer,
useFactory: function (form: NgForm) {
return form;
},
deps: [NgForm]
}`enter code here`
]
})
export class ParentProviderDirective {
constructor() { }
}
<div ParentProvider >
for child
</div>
An alternative to the FormGroupDirective (as described in #blacksheep's answer) is the use of ControlContainer like so:
import { FormGroup, ControlContainer } from "#angular/forms";
export class ChildComponent implements OnInit {
formGroup: FormGroup;
constructor(private controlContainer: ControlContainer) {}
ngOnInit() {
this.formGroup = <FormGroup>this.controlContainer.control;
}
The formGroup can be set in the direct parent or further up (parent's parent, for example). This makes it possible to pass a from group over various nested components, without the need for a chain of #Input()s to pass the formGroup along. In any parent set the formGroup to make it available via ControlContainer in the child:
<... [formGroup]="myFormGroup">
I'm trying kendo ui's (Ver.RC0) NumericTextBoxComponent for angular2 but on the api there is no mention about the component attribute "formControlName".
I'd like to do something like this to validate the form control in the FormGroup:
<kendo-numerictextbox [value]="myvalue"
formControlName ="myNumericFieldFormControl"
>
</kendo-numerictextbox>
Is this possible? If yes, how?
It seems to work in the documentation:
http://www.telerik.com/kendo-angular-ui/components/inputs/numerictextbox/#toc-form-support
#Component({
selector: 'my-app',
template: `
<h4>Only values between -10 and 20 are valid</h4>
<form [formGroup]="form">
<kendo-numerictextbox formControlName="numeric" [min]="-10" [max]="20"></kendo-numerictextbox> <br />
<p *ngIf="form.controls.numeric.errors">{{form.controls.numeric.errors | json}}</p>
</form>
`
})
export class AppComponent {
public form: FormGroup;
constructor(private formBuilder: FormBuilder) {
this.form = this.formBuilder.group({
numeric: [20]
});
}
}
Here is a runnable plunker demo:
http://plnkr.co/edit/FlTfasHq8wvRBzCsWbOK?p=preview
I'm fairly new to angular2 and for the past few days I have been trying to create reusable form components using model driven forms
So lets say we have a component componentA.component.ts
#Component({
selector: 'common-a',
template: `
<div [formGroup]="_metadataIdentifier">
<div class="form-group">
<label>Common A[1]</label>
<div>
<input type="text" formControlName="valueA1">
<small>Description 1</small>
</div>
<div class="form-group">
<label>Common A[2]</label>
<div>
<input type="text" formControlName="valueA2">
<small>Description 2</small>
</div>
</div>
`
})
export class ComponentA implements OnInit{
#Input('group')
public myForm: FormGroup;
constructor(private _fb: FormBuilder) {
}
ngOnInit() {
this.myForm = this._fb.group({
valueA1 : ['', [Validators.required]],
valueA2 : ['', [Validators.required]],
});
}
}
And a component B componentB.component.ts
#Component({
selector: 'common-b',
template: `
<div [formGroup]="_metadataIdentifier">
<div class="form-group">
<label>Common B</label>
<div>
<input type="text" formControlName="valueB">
<small>Description</small>
</div>
</div>
`
})
export class ComponentB implements OnInit{
#Input('group')
public myForm: FormGroup;
constructor(private _fb: FormBuilder) {
}
ngOnInit() {
this.myForm= this._fb.group({
valueB : ['', [Validators.required]]
});
}
}
My question is how can I compose a form using this two sub components without moving the control of the inputs to the main component.
For example a main.component.ts
#Component({
selector: 'main',
template: `
<form [formGroup]="myForm" (ngSubmit)="onSubmit(myForm.value)">
<div>
<common-a [group]="formA"></common-a>
<common-b [group]="formB"></common-b>
<div>
<button>Register!</button>
</div>
</div>
</form>
`
})
export class Main implements OnInit{
#Input('group')
public myForm: FormGroup;
public formA : FormGroup;
public formB : FormGroup;
constructor(private _fb: FormBuilder) {
}
ngOnInit() {
this.myForm = this._fb.group({
//how can I compose these two sub forms here
//leaving the form control names agnostic to this component
});
}
}
The concept behind this idea is to build many complex forms that share some of their building blocks.
That is, I don't want my Main component to know the names of the formControlNames [valueA1,valueA2,valueB] but automagically insert them and update/validate on the top level form group.
Any ideas or points to the right direction would be helpfull.
This can be accomplish by passing in our top level FormGroup to the child component and having the child component add itself into the higher level FormGroup using formGroupName that way the upper level FormGroup needs to know essentially nothing about the lower levels:
main.component.ts
template: `<...>
<common-a [parentForm]="myForm"></common-a>
<...>
We will also get rid of the formA, formB declarations as they are no longer used.
component-a.component.ts [formGroup] is our parent group, formGroupName is how we will identify and attach the component's controls as a group to work in the larger whole (they will nest inside the parent group).
#Component({<...>
template: `
<div [formGroup]="parentForm">
<div class="form-group">
<label>Common A[1]</label>
<div formGroupName="componentAForm">
<input type="text" formControlName="valueA1">
<small>Description 1</small>
</div>
<div class="form-group">
<label>Common A[2]</label>
<div formGroupName="componentAForm">
<input type="text" formControlName="valueA2">
<small>Description 2</small>
</div>
</div>`
})
export class ComponentA implements OnInit {
#Input() parentForm: FormGroup;
componentAForm: FormGroup;
constructor(private _fb: FormBuilder) {}
ngOnInit() {
this.componentAForm = this._fb.group({
valueA1: ['', Validators.required],
valueA2: ['', Validators.required]
});
this.parentForm.addControl("componentAForm", this.componentAForm);
}
}
Here's a plunker (note that I made component B a little more dynamic here just to see if it could be done, but the implementation above for is equally applicable to B): http://plnkr.co/edit/fYP10D45pCqiCDPnZm0u?p=preview