Angular + Material

编程入门 行业动态 更新时间:2024-10-26 11:18:08
本文介绍了Angular + Material - 如何使用表单组处理多个复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我有一个从后端获得的兴趣列表.我希望用户能够选择他们想要的兴趣.我将只存储他们在数据库中检查的兴趣,并在他们加载页面时预先填充.但首先我需要获得用户选择的这些兴趣.

interestponent.ts

export class InterestsComponent 实现 OnInit {兴趣表格组:表格组兴趣:任何;选择:任何;构造函数(公共利益服务:InterestService,私有formBuilder:FormBuilder,) { }ngOnInit() {this.interestFormGroup = this.formBuilder.group({兴趣:this.formBuilder.array([])});this.interestService.all().subscribe((res) => {this.interests = res;});}改变() {控制台日志(this.interestFormGroup.value);}}

interestponent.html

<div class="兴趣列表"><form [formGroup]="interestFormGroup"><div *ngFor="让利益的利益" ><mat-checkbox class="example-margin" formNameArray="interests" (change)="change()">{{interest}}</mat-checkbox>

</表单>

在我的console.log 中的change 事件中,它显示没有值被添加到interestFormGroup 中的interests 数组中.即使复选框被选中.

解决方案

你应该手动添加控件到 FormArray 像:

this.interests = res;const formArray = this.interestFormGroup.get('interests') as FormArray;this.interests.forEach(x => formArray.push(new FormControl(false)));

然后更改模板如下:

<ng-container formArrayName="interests"><div *ngFor="let Interest of Interest; let i = index" ><mat-checkbox class="example-margin" [formControlName]="i">{{兴趣}}</mat-checkbox>

</ng-容器><按钮>提交</表单>

当您提交表单时,您需要将 FormArray 值转换为您想要的结果:

submit() {const 结果 = Object.assign({},this.interestFormGroup.value, {兴趣:this.interests.filter((x, i) => !!this.interestFormGroup.value.interests[i])});控制台日志(结果);}

替代解决方案是监听 change 事件并手动添加和删除 FormArray 的值:

onChange(事件){const Interest = <FormArray>this.interestFormGroup.get('interests') as FormArray;如果(事件.检查){兴趣.推(新的FormControl(事件.源.值))} 别的 {const i =interests.controls.findIndex(x => x.value === event.source.value);Interest.removeAt(i);}}

Stackblitz 示例

I have a list of interests i am getting from the backend. I want a user to be able to select the interests they want. I will store only the interests they checked in the DB and pre-populate when they load the page. But first i need to get these interests the user has selected.

interestponent.ts

export class InterestsComponent implements OnInit {

  interestFormGroup : FormGroup
  interests:any;
  selected: any;


  constructor(public interestService: InterestService, private formBuilder: FormBuilder,
  ) { }

  ngOnInit() {

    this.interestFormGroup = this.formBuilder.group({
      interests: this.formBuilder.array([])
    });


    this.interestService.all().subscribe((res) => {

      this.interests = res;

    });

  }

  change() {
    console.log(this.interestFormGroup.value);
  }

}

interestponent.html

<div id="interest">

    <div class="interest-list">

        <form [formGroup]="interestFormGroup">
            <div *ngFor="let interest of interests" >
                <mat-checkbox class="example-margin" formNameArray="interests" (change)="change()">{{interest}}</mat-checkbox>
            </div>
        </form>

    </div>

</div>

In my console.log on the change event it shows there is no values being added to the interests array within the interestFormGroup. Even tho the checkboxes are checked.

解决方案

You should add controls to FormArray manually like:

this.interests = res;
const formArray = this.interestFormGroup.get('interests') as FormArray;
this.interests.forEach(x => formArray.push(new FormControl(false)));

then change template as follows:

<form [formGroup]="interestFormGroup" (ngSubmit)="submit()">
   <ng-container formArrayName="interests">
      <div *ngFor="let interest of interests; let i = index" >
         <mat-checkbox class="example-margin" [formControlName]="i">
           {{interest}}
         </mat-checkbox>
      </div>
   </ng-container>
   <button>Submit</button>
</form>

And when you will submit form you need to transform FormArray values to your desired result:

submit() {
  const result = Object.assign({}, 
    this.interestFormGroup.value, { 
      interests: this.interests
        .filter((x, i) => !!this.interestFormGroup.value.interests[i])});

  console.log(result);
}

Alternative solution is listen change event and manually add and remove value to FormArray:

<div *ngFor="let interest of interests; let i = index" >
   <mat-checkbox class="example-margin" 
                (change)="onChange($event)" [value]="interest">{{interest}}</mat-checkbox>
</div>

onChange(event) {
  const interests = <FormArray>this.interestFormGroup.get('interests') as FormArray;

  if(event.checked) {
    interests.push(new FormControl(event.source.value))
  } else {
    const i = interests.controls.findIndex(x => x.value === event.source.value);
    interests.removeAt(i);
  }
}

Stackblitz example

这篇关于Angular + Material - 如何使用表单组处理多个复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-21 13:47:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1004370.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Angular   Material

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!