Angular 5 multiple checkbox 多项复选框 加载以及传值解决方案

阅读更多

Angular 5 multiple checkbox 多项复选框 加载以及传值解决方案

 

我们碰到FormControl 响应式表单中有多选列表的Checkboxs时,在加载和选中或不选中想动态双向绑定值以及页面显示会遇到一些问题。下面我们来深究一下解决方案。

 

接下来这段代码需要贴到在线js 调试工具 中去运行结果

将以下代码贴到这个地址 js调试工具的src/app.ts 文件中去

 

代码如下:

 

//our root app component
import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import { Component } from '@angular/core';
import { FormControl, FormGroup, FormArray, FormBuilder, Validators } from '@angular/forms';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

@Component({
  selector: 'my-app',
  template: `

  
{{data.email}}
API类型至少选择一项! API类型至少选择一项! API类型至少选择一项!
Form values: {{myForm.value | json}}
Form values: {{useremail.invalid | json}}
Form values: {{useremail.status | json}}
Form values: {{myForm.status | json}}
`, }) export class App { emails = [{email:"email1"},{email:"email2"},{email:"email3"},{email:'email4'}] myForm: FormGroup; selectEmails:Array=[{email:"email1"},{email:"email2"}]; constructor(private fb: FormBuilder) { } ngOnInit() { this.myForm = this.fb.group({ useremail: this.fb.array([],[Validators.required,Validators.minLength(1)]), appkey:['',Validators.required], secret:['',Validators.required] }); const emailFormArray = this.myForm.controls.useremail; this.selectEmails.forEach((em)=> { let index= emailFormArray.controls.findIndex(x=>x.value==em.email); if(index==-1){ emailFormArray.push(new FormControl(em.email)); } }); this.myForm.patchValue({appkey:"sdfasdf",secret:"wwwww"}); } isChecked(data:any):Boolean{ return this.selectEmails.find((item)=>{ return item.email==data.email }); } get useremail(){return this.myForm.get('useremail');} get appkey(){return this.myForm.get('appkey');} get secret(){return this.myForm.get('secret');} save($event,values){ console.log("form values: %o",values); } onChange(email:string, isChecked: boolean) { const emailFormArray = this.myForm.controls.useremail; if(isChecked) { let index = emailFormArray.controls.findIndex(x => x.value == email); if(index==-1){ emailFormArray.push(new FormControl(email)); } } else { let index = emailFormArray.controls.findIndex(x => x.value == email) emailFormArray.removeAt(index); } } } @NgModule({ imports: [ BrowserModule, FormsModule, ReactiveFormsModule ], declarations: [ App ], bootstrap: [ App ] }) export class AppModule {}

 

你可能感兴趣的:(Angular2)