Did you try having your component bind to the form control? Each
application could use FormBuilder and FormControls like any other form but
the actual control would be backed by your reusable input component. This
does make your reusable component a very dumb (as in dumb vs. smart)
control but using projection/transclusion you can still control look and
feel and how errors are displayed. Using transclusion would have you break
your shared component down a little further (ie. label component, error
component, etc.) and that would drive the example here to be a little more
complex, but conceptually something along these lines:
**myComponent**
@Component({
selector: 'myComponent',
directives: [REACTIVE_FORM_DIRECTIVES ],
template: `<input type="text" ... [formControl]="inputFormControl"
... />`
})
export class MyComponent {
@Input() inputFormControl: FormControl
}
**app1, but there are app2 etc...**
import {MyComponent} from './myComponent';
@Component({
selector: 'myApp',
template:`
<form #myForm="ngForm" (ngSubmit)="submited()">
<myComponent [inputFormControl="username"></myComponent>
</form>`,
directives: [REACTIVE_FORM_DIRECTIVES, FormComponent, MyComponent]
})
export class MyComponent {
submitted() {
}
}
On Saturday, July 9, 2016 at 3:29:42 PM UTC-4, hani wrote:
>
> I would like to create a reusable component which has a fixed look and
> functionality that can be used across multiple applications. It contains
> `<input>` elements that require validation, so they need to be associated
> with the parent form where the component is defined. How do you associate
> the `input` in this child component with `ngForm` in its parent component?
>
> **myComponent**
>
> @Component({
> selector: 'myComponent',
> template: `<div><input type="text" [(ngModel)]="text" /></div>` //how
> add ngControl and associate with parent form?
> })
> export class MyComponent {
> text: string;
> }
>
>
>
> **app1, but there are app2 etc...**
>
> import {MyComponent} from './myComponent';
>
> @Component({
> selector: 'myComponent',
> template: `<form #myForm="ngForm"
> (ngSubmit)="submited()"><myComponent></myComponent></form>`,
> directives: [MyComponent]
> })
> export class MyComponent {
> submitted() {
> }
> }
>
>
>
> In each app, `myComponent` has to have its `ngControl` associated with the
> `ngForm` so it can be validated and accessed the same way as a regular
> `ngControl` which is defined directly inside of `ngForm`. Also note that
> adding `ngControl` without having a direct `ngForm` parent will throw an
> error 'no container found.'.
>
--
You received this message because you are subscribed to the Google Groups
"AngularJS" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.