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

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

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

<form [formGroup]="myGroup" (submit)="submit(myGroup.value)">
    <div class="row">
      <div class="col-sm-4" *ngFor="let info of myGroup.controls['myInfo'].controls; let i = index">

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

      </div>
    </div>

<div class="row">
  <button class="form-control btn-sub" type=”submit”>
    Submit Details
  </button>
</div>

我的组件class:

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

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,如果未选中,则删除从表单数组中选择的电子邮件。

你可以参考下面link:

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

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