Reputation: 293
In an Angular 2 Form, Trying to get data through ngSubmit. I can assign both ngModel and ngControl properties within my form component without problem, however in the sub-component MyInput, I cannot assign ngControl without a "no provider error". Plunker here http://plnkr.co/edit/LauhEz6vMaEmIg0hceoj?p=preview
directives: [CORE_DIRECTIVES, FORM_DIRECTIVES, MyInput],
template: ` <div>
<form #hf="ngForm" (ngSubmit)="onSubmit(hf.value)">
<div>
In Form: <input type='text' [ngControl]="inform" [(ngModel)]="theValue" [required]="req" #spy >
<br>Classes: {{spy.className}}
<br>
<br>In Component: <my-input [props]='prop'></my-input>
<br>In Component: <my-input [props]='prop2'></my-input>
</div>
<button type="submit" [hidden] = "!editing">Save</button>
<button type="button" (click)="cancelClick()" [hidden] = "!editing">Cancel</button>
<button type="button" (click)="setEdit(true)" [hidden] = "editing">Edit</button>
</form>
Form Values {{data}}
</div>
`
Sub Component template:
@Component({
selector: 'my-input',
directives: [FORM_DIRECTIVES],
template: `
<input type='text'
[(ngModel)]="props.Value"
Error if I add this
[ngControl]="props.id"
Is there something I need to pass to the Sub Component from the form?
Upvotes: 12
Views: 2388
Reputation: 1239
UPDATE: Using this method, the parent form does not have the ability out of the box to determine its validity based on the validity of subcomponents.
As a workaround, you can try wrapping the sub-component in its own form element.
@Component({
selector: 'my-input',
directives: [FORM_DIRECTIVES],
template: `
<form> <--------------
<input type='text'
[(ngModel)]="props.Value"
[ngControl]="props.id" />
</form>
Not ideal, but it's the only way I could compose a form with sub-components without using dynamic forms https://angular.io/docs/ts/latest/cookbook/dynamic-form.html
Upvotes: 0
Reputation: 1726
Isn't it a problem that the prop is not available at the time of ngControl binding / execution... what if you provided a default controll in the component and then make a refference to the one from the props
in ngOnChange
which is executed at the time when the props are really available.
Upvotes: 1