发送包含复选框值的Angular 6表单不适用于模板驱动的表单

sending Angular 6 form including checkbox values not working with template driven forms

我正在尝试使用formbuilder传递包含Angular 6表单中的复选框的表单值,但是我无法从复选框中读取值。我正在从所有其他输入字段获取所有值,但只有复选框没有响应这是我的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<form [formGroup]="myGroup" (submit)="submit(myGroup.value)">
   
     

            <label for="{{labelValue[i].name}}"> {{labelValue[i].label}}
            <input type="{{labelValue[i].type}}" class="{{labelValue[i].class}}" [formControl]="info">
          </label>

     
   


  <button class="form-control btn-sub" type=a€?submita€?>
    Submit Details
  </button>

我的组件类:

从'src / app / Services / Proposal-service / proposal.service'导入{ProposalService,CustomerDetails,ProposalNumber};

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
export interface InputType{
  name:string;
  type: string;
  label: string;

  class:string;
}
export class ProposalComponent implements OnInit {

  public labelValue: InputType[] = [
  {name:"fname",type:"text",label:"First Name", class:"form-control"},
  {name:"form60",type:"checkbox",label:"Is Collection Of form 60", class:"form-control"},
  {name:"eia-num",type:"number",label:"EIA Number", class:"form-control"}
];
  title ="Customer Details";
  details: Observable<CustomerDetails>;
  pNumber: ProposalNumber ;

  public information: CustomerDetails[] = [
    {name:"First Name", value:""},//
 {name:"IsCollectionOfform60", value:true},
    {name:"EIA Number", value:""}
  ];

  myGroup : FormGroup;

  constructor(private formBuilder: FormBuilder,
   private _proposalService: ProposalService) { }

  ngOnInit() {

  this.myGroup = this.formBuilder.group({
    myInfo: this.constructFormArray()
  });

  this.pNumber = <ProposalNumber>{proposalNumber: 0 ,message:"", status:""};

  }


  constructFormArray()
  {
    const arr = this.information.map(cat => {
      return this.formBuilder.control(cat.value);
    });
    return this.formBuilder.array(arr);

  }


  submit(form){
    //this.loading = true;
    console.log(form);
    let mySelectedAddon = form.myInfo.map((currentValue,i)=> {
      return {"name" : this.information[i].name ,"value" : currentValue}
      }
    );
    console.log(mySelectedAddon);
    this._proposalService.loadCustomer(mySelectedAddon).subscribe((res: ProposalNumber) =>{
      //this.loading = false;
        console.log(res);
        this.pNumber.proposalNumber = res.proposalNumber;
        this.pNumber.message = res.message;
        console.log(this.pNumber.proposalNumber);
        return this.myGroup.value;
  });
}
}

您需要使用'change'事件并将相应的输入值和事件传递给onChange方法,在其中检查是否已选中它,然后将相应的值添加到formarray中,如果未选中,则从表格数组。

您可以参考以下链接:

https://stackblitz.com/edit/angular-rskaug?file=src/app/app.component.ts

以上示例可用于动态获取复选框的值。