Javascript 如何使用http请求中的数组向角度表单添加动态输入字段
我已经尝试了所有的方法,并检查了相关的stackoverflow问题,但在这里提问没有任何效果。我必须创建一个ui,在这个ui中,通过选择下拉菜单进行api调用,并以数组的形式接收数据。基于这个数组,我想在我的表单中添加尽可能多的字段,因为数组中有很多元素。我试着用FormArray,但没用。由于我不断收到与无法找到具有指定名称“name”的控件相关的错误。我尝试使用使formcontrol字段动态化,但仍然得到相同的错误 这是我试过的代码 .ts文件Javascript 如何使用http请求中的数组向角度表单添加动态输入字段,javascript,angular,angular-directive,Javascript,Angular,Angular Directive,我已经尝试了所有的方法,并检查了相关的stackoverflow问题,但在这里提问没有任何效果。我必须创建一个ui,在这个ui中,通过选择下拉菜单进行api调用,并以数组的形式接收数据。基于这个数组,我想在我的表单中添加尽可能多的字段,因为数组中有很多元素。我试着用FormArray,但没用。由于我不断收到与无法找到具有指定名称“name”的控件相关的错误。我尝试使用使formcontrol字段动态化,但仍然得到相同的错误 这是我试过的代码 .ts文件 import { Component, O
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators, FormControl, FormArray } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-calculator',
templateUrl: './calculator.component.html',
styleUrls: ['./calculator.component.scss']
})
export class CalculatorComponent implements OnInit {
title = 'Formula Calculation Page';
configUrlProducts = 'http://localhost:3000/data/products';
configUrlProductFieldsData = 'http://localhost:3000/data/getproductfields/';
angForm: FormGroup;
ruleset_data=[];
ruleset_data_length=0;
products: any = [];
selected_product_id;
syntax_error=false
show_form=false;
arr=[{'name':''},{'class':''},{'tree':''}];
temp;
// products=[{"id":1,"name":'Product 1'},{"id":2,"name":'Product 2'},{"id":3,"name":'Product 3'}]
constructor(private fb: FormBuilder,private http: HttpClient) {
console.log("inside constructor")
// this.createForm();
// this.fetch_products();
}
// convenience getters for easy access to form fields
get f() { return this.angForm.controls; }
get t() { return this.f.fields as FormArray; }
ngOnInit() {
console.log("inside ngonit");
this.angForm = this.fb.group({
fields: new FormArray([])
});
for(var i=0;i<3;i++){
this.temp=this.arr[i];
this.t.push(this.fb.group({'name':''}))
}
// this.arr.forEach(item=>{
// this.t.push(this.fb.group(item))
// })
console.log(this.angForm)
this.getProducts();
}
getProducts() {
console.log("inside get products");
this.products = [];
this.http.get(this.configUrlProducts).subscribe((res)=>{
console.log(res);
this.products = res["data"];
});
}
fetch_ruleset_data(value: string){
this.selected_product_id=value;
console.log("inside get rule data");
this.ruleset_data = [];
this.http.get(this.configUrlProductFieldsData+value).subscribe((res)=>{
console.log(res);
this.ruleset_data = res["data"];
this.show_form=true;
console.log(this.angForm);
this.ruleset_data_length=res["data"].length;
});
}
onSubmit(value){
console.log(value);
// var data=value;
// data["no_of_variables"]=this.ruleset_data_length;
// data["product_id"]=this.selected_product_id;
// // value=value+this.ruleset_data_length;
// // var formula=JSON.parse(value);
// console.log("final data before sending to api",data);
// return this.http.post('http://localhost:3000/formula/addformula', data)
// .subscribe((res)=>{
// console.log(res);
// })
}
validateFormula=(c: FormControl)=> {
console.log(c.value,typeof c.value);
var data={};
data['formula']=c.value;
data["no_of_variables"]=this.ruleset_data_length;
data["product_id"]=this.selected_product_id;
return this.http.post('http://localhost:3000/formula/validateformula', data)
.subscribe((res)=>{
// console.log("inside validation after api call",res)
// console.log(res["error"])
if(res["error"]){
console.log("inside error block",res);
this.syntax_error=true;
// this.angForm.setErrors({ 'invalid': true });
// return true;
return {
validateFormula: {
valid: true
}
}
}else{
this.syntax_error=false;
// this.angForm.setErrors({ 'invalid': false });
// return true;
return {
validateFormula: {
valid: true
}
}
}
})
// let EMAIL_REGEXP;
// return EMAIL_REGEXP.test(c.value) ? null : {
// validateEmail: {
// valid: false
// }
// };
}
// fetch_ruleset_data(value: string){
// console.log(value);
// }
}
从'@angular/core'导入{Component,OnInit};
从'@angular/forms'导入{FormGroup,FormBuilder,Validators,FormControl,FormArray};
从'@angular/common/http'导入{HttpClient};
@组成部分({
选择器:“应用计算器”,
templateUrl:“./calculator.component.html”,
样式URL:['./calculator.component.scss']
})
导出类计算器组件实现OnInit{
标题='公式计算页';
configUrlProducts=http://localhost:3000/data/products';
configUrlProductFieldsData=http://localhost:3000/data/getproductfields/';
angForm:FormGroup;
规则集_数据=[];
规则集\数据\长度=0;
产品:任何=[];
所选产品标识;
语法错误=false
show_form=false;
arr=[{'name':'''},{'class':''''},{'tree':''''}];
临时雇员
//products=[{“id”:1,“名称”:“产品1”},{“id”:2,“名称”:“产品2”},{“id”:3,“名称”:“产品3”}]
构造函数(私有fb:FormBuilder,私有http:HttpClient){
log(“内部构造函数”)
//这个.createForm();
//这个。fetch_products();
}
//方便的getter,便于访问表单字段
get f(){返回this.angForm.controls;}
get t(){将此.f.fields作为FormArray;}
恩戈尼尼特(){
控制台日志(“ngonit内部”);
this.angForm=this.fb.group({
字段:新表格([])
});
对于(var i=0;i{
//此.t.push(此.fb.group(项目))
// })
console.log(this.angForm)
这个.getProducts();
}
getProducts(){
console.log(“内部获取产品”);
这是产品=[];
this.http.get(this.configUrlProducts).subscribe((res)=>{
控制台日志(res);
this.products=res[“数据”];
});
}
获取规则集数据(值:字符串){
此。所选产品\u id=值;
log(“内部获取规则数据”);
this.ruleset_data=[];
this.http.get(this.configUrlProductFieldsData+值)。订阅((res)=>{
控制台日志(res);
this.ruleset_data=res[“data”];
此.show_form=true;
console.log(this.angForm);
this.ruleset_data_length=res[“data”].length;
});
}
onSubmit(值){
console.log(值);
//var数据=价值;
//数据[“没有变量”]=此.ruleset\u数据长度;
//数据[“产品标识”]=此。所选产品标识;
////value=value+this.ruleset\u data\u length;
////var formula=JSON.parse(值);
//console.log(“发送到api之前的最终数据”,数据);
//返回此.http.post('http://localhost:3000/formula/addformula",数据)
//.订阅((res)=>{
//控制台日志(res);
// })
}
validateFormula=(c:FormControl)=>{
console.log(c.value,c.value的类型);
变量数据={};
数据['formula']=c.值;
数据[“没有变量”]=此.ruleset\u数据长度;
数据[“产品标识”]=此。所选产品标识;
返回此.http.post('http://localhost:3000/formula/validateformula",数据)
.订阅((res)=>{
//log(“api调用后的内部验证”,res)
//console.log(res[“error”])
if(res[“error”]){
日志(“内部错误块”,res);
this.syntax_error=true;
//this.angForm.setErrors({'invalid':true});
//返回true;
返回{
validateFormula:{
有效:正确
}
}
}否则{
this.syntax_error=false;
//this.angForm.setErrors({'invalid':false});
//返回true;
返回{
validateFormula:{
有效:正确
}
}
}
})
//让我们发电子邮件给REGEXP;
//返回电子邮件\u REGEXP.test(c.value)?空:{
//验证邮件:{
//有效:假
// }
// };
}
//获取规则集数据(值:字符串){
//console.log(值);
// }
}
.html文件
<!-- app.component.html -->
<div class="container">
<h1>
Welcome to {{title}}!!
</h1>
<select class="custom-select" (change)="fetch_ruleset_data($event.target.value)">
<option value="" disabled>Choose your product</option>
<option *ngFor="let product of products; let i = index" [value]="product.id">
{{product.name}}
</option>
</select>
<div *ngIf="show_form==true">
<form [formGroup]="angForm" (ngSubmit)="onSubmit(angForm.value)">
<div *ngFor="let item of t.controls; let i = index">
<div [formGroup]="item">
<input [formControlName]='item'>
</div>
</div>
<button type="submit">Submit</button>
</form>
</div>
<br />
</div>
欢迎来到{{title}}!!
选择你的产品
{{product.name}
提交
在过去的两天里,我们一直在努力解决这个问题,非常感谢您的帮助。我对angular是一个新手,目前正在学习它,这可能是一件简单的事情,但我目前无法理解它,需要您的帮助 我不知道你收到的数据。把你收到的数据想象一下,你的例子表明这有点像
[{'name':''},{'class':''},{'tree':''}];
[{col:'name',value:''},{col:'class',value:''},{col:'tree',value:''}];
真是一个可怕的数据。这是更“自然”收到一些像
[{'name':''},{'class':''},{'tree':''}];
[{col:'name',value:''},{col:'class',value:''},{col:'tree',value:''}];
但我想这是另一个问题。“键”是在收到数据时创建一个FormGroup,并(在您的情况下,创建一个具有字段名称的数组)在数组上迭代
this.http.get(this.configUrlProducts).subscribe((res:any[])=>{
this.formGroup=new FormGroup({}) //<--create a formGroup empty
this.fields=[] //<--create an array empty
res.forEach(x=>{
const key=Object.keys(x)[0]
const value=x[key]
this.formGroup.addControl(key,new FormControl(value))
this.fields.push(key)
})
});
this.http.get(this.configUrlProducts).subscribe((res:any[])=>{
this.formGroup=newformgroup({})//{
this.formGroup=newformgroup({})//{
常数键=x列
常量值=x.value
this.formGroup.addControl(键,新FormControl(值))
})
这个.fields=res;
});
如果您收到一个包含名称、值、验证器、标签的对象数组,则此想法可以扩展,因为您可以使用{{field.label}来显示标签
如果您收到['a'、'b'、'c'],您可以使用
this.http.get(this.configUrlProducts).subscribe((res:any[])=>{
this.formGroup=new FormGroup({}) //<--create a formGroup empty
res.forEach(x=>{
this.formGroup.addControl(x,new FormControl(''))
})
this.fields=res;
});
<form [formGroup]="formGroup">
<div *ngFor="let field of fields">
<input [formControlName]="field">
</div>
</form>
this.http.get(this.configUrlProducts).subscribe((res:any[])=>{
this.formGroup=newformgroup({})//{
this.formGroup.addControl(x,新FormControl(“”))
})
这个.fields=res;
<form [formGroup]="myForm">
<ng-container *ngFor="let group of myForm.controls |keyvalue">
<div [formGroup]="group.value">
<button type="button" (click)="onAddProduct(group.value)">Add Product</button>
<div formArrayName="productList">
<div *ngFor="let item of productArray(group.value).controls; let i = index">
<label for="">Your row</label>
<input [formControlName]="i">
<button (click)="removeProduct(group.value,i)">remove</button>
</div>
</div>
</div>
<pre>
{{myForm?.value|json}}
</pre>
</ng-container>
</form>
name = 'Angular';
public myForm: FormGroup;
ngOnInit() {
this.myForm = new FormGroup({});
for(let item of ['item1']) {
this.myForm.addControl(item,
new FormGroup({
name: new FormControl(),
productList: new FormArray([])
})
)
}
}
onAddProduct(group:FormGroup) {
(group.get('productList') as FormArray).push(new FormControl())
}
productArray(group:FormGroup):FormArray
{
return group.get('productList') as FormArray;
}
removeProduct(group:FormGroup,index:number)
{
(group.get('productList') as FormArray).removeAt(index)
}