4

I am using Angular2 to create a web application. I have several data entry screens where the user must input a postal address which is part of a larger data entry for entities like Company or Person.

So naturally I would like to create an Address Form Component that could be reused as a subform and somehow embedded or included within larger forms. This seems like it should be possible but I haven't been able to create an example or find and example. I've tried to create a subcomponent that has a FormBuilder as an input, but this doesn't work.

the problem for me is that I can't seem to successfully communicate the enclosing < form > tag to my html template.

Does anyone know of an approach for this?

1

1 Answer 1

5

only for <= Angular <= 2.0.0 RC

I don't know if this is a good approach but it seems to work

@Component({
  selector: 'address-form',
  providers: [],
  styles: [':host {display: inline-block; border: 1px solid blue;}'],
  template: `

    <input [ngFormControl]="street">
    <input [ngFormControl]="zip">
  `,
  directives: []
})
export class AddressForm {
  street = new Control('', Validators.minLength(3));
  zip = new Control('', Validators.required);
  isSet:boolean;
  @Input() group;
  constructor() {}

  ngOnChanges() {
    setTimeout(()=> {
      this.group.control.addControl('street', this.street);
      this.group.control.addControl('zip', this.zip);
    });
  }
}
  <form #f="ngForm">
    <input ngControl="custId"> 
    <address-form ngControlGroup="address" #addrGroup="ngForm" [group]="addrGroup"></address-form>
  </form>

Plunker example

See also this comment from Kara with Plunker https://github.com/angular/angular/issues/10251#issuecomment-238737954

Sign up to request clarification or add additional context in comments.

4 Comments

The punker is not running. Showing following error GET https://npmcdn.com/@angular/[email protected]/core.umd.js 404 ()
It only works for an old Angular version. I think the better approach is to implement ControlValueAccessor in the child component anyway.
I have found a template driven approach here as well. Which is very good. stackoverflow.com/questions/42352680/…. Modified Plunker is here : plnkr.co/edit/vuCLmgSckv63GjMipa0m?p=preview
Thanks for the links.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.