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

Jep*_*zen 5 angular angular-forms

我需要首先调用 API 获取表单中的一些值,然后提交它。我喜欢避免使用带有隐藏输入的表单,并希望即时创建它。我的伪代码

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
}
Run Code Online (Sandbox Code Playgroud)

我希望我的浏览器重定向到我提交表单的页面。

编辑:对不起..!我主要关心的是如何提交此表格。不是获取数据并填充表单。我的代码只是一个模板..这是我缺少的 this.signForm.submit() 方法

Jos*_*tič 5

您在这里犯的错误是,您无法在mydata不订阅数据的情况下访问数据,因为http.get()返回Observable

您可以使用订阅

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);
 });
}
Run Code Online (Sandbox Code Playgroud)

或者异步/等待

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);
}
Run Code Online (Sandbox Code Playgroud)

更新:

我已经尝试了几种方法来在 Angular 中使用重定向发送发布请求。但唯一对我有用的是创建隐藏的<form>

为此我创建了这个方法

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();
  }
Run Code Online (Sandbox Code Playgroud)

这里最好的方法是在没有 的情况下提交它,appendChild()但是它会产生这个错误

由于表单未连接,提交被取消。


小智 1

如果您的表单上没有条件(例如必填字段或受限字段),您可以像这样使用表单生成器。

constructor(
  fb: FormBuilder,
  http: HttpClient
) {
  http.get(...).subscribe(response => fb.group(response));
}
Run Code Online (Sandbox Code Playgroud)

Tha 应该从直接的 JSON 对象构建表单。问题是您必须提前了解表单模型以避免出现错误。反应式形式并不是为此而设计的。

相反,您应该依赖模板驱动的表单。官方文档可以告诉你更多信息。

您可以使用Object.keys它来迭代键。

constructor(
  fb: FormBuilder,
  http: HttpClient
) {
  http.get(...).subscribe(response => fb.group(response));
}
Run Code Online (Sandbox Code Playgroud)
rawResponse$ = this.http.get(...).pipe(share());
keys$ = this.rawResponse$.pipe(response => Object.keys(response));
Run Code Online (Sandbox Code Playgroud)

或者类似的东西。