简体   繁体   English

如何动态创建表单并在 Angular 7 中提交?

[英]How can I create a form dynamically and submit it in Angular 7?

I need to first call a API get some values put in my form then submit it.我需要先调用 API 获取一些值放在我的表单中然后提交它。 I like to avoid having a form with hidden inputs and want to create it on the fly.我喜欢避免使用带有隐藏输入的表单并希望即时创建它。 My pseudo code我的伪代码

submitMyform() {
  //first i call an API and get some data
  var mydata = this.http.get()...

 this.signForm = new FormGroup({
  'Name': new FormControl(mydata.name),
  'Age': new FormControl(mydata.age)   
 });

  this.signForm.submit() //Wished this method existed
}

I want my browser to redirect to the page I am submitting the form to.我希望我的浏览器重定向到我提交表单的页面。

EDIT: Sorry..!编辑:对不起..! My concerns was mostly how to submit this form.我最关心的是如何提交这个表格。 Not to get the data and populate the form.不获取数据并填充表单。 My code was just a template.. It is the this.signForm.submit() method I am missing我的代码只是一个模板..这是我缺少的 this.signForm.submit() 方法

The mistake you are doing here is that you can't access data in mydata without subscribing to it because http.get() returns Observable你在这里做的错误是你不能在不订阅的情况下访问mydata数据,因为http.get()返回Observable

You can use subscribe您可以使用订阅

submitMyform() {
  //first i call an API and get some data
  var mydata = this.http.get()...
 mydata.subscribe((data) =>{
   this.signForm = new FormGroup({
    'Name': new FormControl(mydata.name),
    'Age': new FormControl(mydata.age)   
   });
   this.http.post('url', this.signForm);
 });
}

Or async/await或异步/等待

async submitMyform() {
  //first i call an API and get some data
  var mydata = await this.http.get().toPromise();
  this.signForm = new FormGroup({
    'Name': new FormControl(mydata.name),
    'Age': new FormControl(mydata.age)   
  });
 this.http.post('url', this.signForm);
}

Update:更新:

I have tried several things to send post request with redirect in Angular.我已经尝试了几件事来在 Angular 中通过重定向发送 post 请求。 But the only one which worked for me was creating hidden <form>但唯一对我有用的是创建隐藏的<form>

For this I have created this method为此,我创建了此方法

submitForm(action, method, formGroup: FormGroup) {
    const form = document.createElement('form');
    form.style.display = 'none';
    form.method = method;
    form.action = action;
    let input;
    for (const [key, value] of Object.entries(formGroup.value)) {
      input = document.createElement('input');
      input.name = key;
      input.id = key;
      input.value = value;
      form.appendChild(input);
    }
    document.body.appendChild(form);
      form.submit();
  }

The best way here would be to submit it without the appendChild() but then it would produce this error这里最好的方法是在没有appendChild()情况下提交它,但它会产生这个错误

Submit was canceled because form is no connected.由于表单未连接,提交被取消。

If you don't have conditions on your form (like required fields, or restricted fields), you can use the form builder like so.如果您的表单上没有条件(如必填字段或受限字段),您可以像这样使用表单构建器。

constructor(
  fb: FormBuilder,
  http: HttpClient
) {
  http.get(...).subscribe(response => fb.group(response));
}

Tha should build the form from a direct JSON object. Tha 应该从直接的 JSON 对象构建表单。 The issue is that you have to know your form model in advance to avoid getting errors.问题是你必须提前知道你的表单模型以避免出错。 And reactive forms aren't made for that.反应式形式不是为此而设计的。

Instead, you should rely on template driven forms.相反,您应该依赖模板驱动的表单。 The official documentation can tell you more.官方文档可以告诉你更多。

You can use Object.keys to iterate over the keys.您可以使用Object.keys迭代键。

rawResponse$ = this.http.get(...).pipe(share());
keys$ = this.rawResponse$.pipe(response => Object.keys(response));
<ng-container *ngFor="let key of keys$ | async">
  <input type="text" [(ngModel)]="(rawResponse$ | async)?[key]">
</ng-container>

Or something similar.或者类似的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM