当前位置: 动力学知识库 > 问答 > 编程问答 >

How do new forms work in angular2

问题描述:

The best tutorials I can find out there, crucially, this one.... only work for the deprecated (and soon to be completely gone) forms stuff.

As far as I can tell this is the only documentation on the new forms:

https://docs.google.com/document/u/1/d/1RIezQqE4aEhBRmArIAS1mRIZtWFf6JxN_7B4meyWK0Y/pub

I managed to get the @angular/forms installed (with help from here) and can get a single-level form to work by copy-pasting the examples in docs from above... however, I'm having a hell of a time implementing anything else or anything that doesn't define the entire form structure at compile time.

I'm hoping to build an app that allows me to drag-drop and remove form questions. Further, some of the questions will have sub-questions as well and I'd also like to pull the questions from a service (and thus won't be able to hard-code the form layout ahead of time as the docs show)

It seems that, at least for my use case, it would be best to have one component for each 'question'. Each component would then have it's own form in it's template.

That is, I'd like ParentComponent to have it's template look something like this:

<h1>Parent Component</h1>

<form (submit)="onSubmit()" *ngFor='let question of questions'>

<subform [question]='question'></subform>

</form>

And then in the subform we'd build each template based on what "Question" got sent in. For the sake of an example, something like (apologies for the fact this probably contains errors, I'm writing it directly in here... will try to plunkr later):

import {Component, Input} from '@angular/core';

@Component({

selector: 'subform',

template: `

<h3>{{question.label}}</h3>

<form *ngFor='let option of question.getOptions()'

<input type="radio" name="gender" value="[option]" checked> {{option}}<br>

</form>

`

})

export class ChildComponent {

@Input() question

}

I can't seem to figure out the syntax to make something like this work AND give me references so I could update data as the form options changed. Every page or tutorial on this subject seems to give different answers (including the angular documentation of forms (which gives "you are using deprecated stuff" warnings)... and all are different than the office change docs above.

FormGroup seems to be the place I should be looking, but that appears to require the whole form structure be built at compile time... (the data can be updated later according to docs if you search for "Bind existing form with async one-way binding"... but I can't seem to make building the form structure happen dynamically at runtime)

网友答案:

check this out: https://angular.io/docs/ts/latest/cookbook/dynamic-form.html

maybe it can help you

分享给朋友:
您可能感兴趣的文章:
随机阅读: