繁体   English   中英

如何在 angular 10 中使用 FromControl 初始化值 mat-selection-list

[英]How init value mat-selection-list with FromControl in angular 10

我无法用 FormControl 的动态值初始化我的组件 Mat-Selection-List。

该表单似乎有效,但从未检查过我列表中的值。

///ts
  ngOnInit(): void {
    this.categoryService.getAllCategory()
  .subscribe(data => {
      this.cbxCategory = data;
    },
    error => console.log(error)
  );
    this.authService.getUser()
      .subscribe(data => {
          this.user = data;
        },
        error => console.log(error),
        
        ()=>this.initForm()
      );
  }

  private initForm() {
    this.editUserForm = this.formBuilder.group({
      email: new FormControl(this.user.email, [Validators.required,Validators.pattern("^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,6}$"),Validators.maxLength(50)]),
      password: new FormControl(''),
      passwordConfirm: new FormControl(''),
      lstCat: new FormControl(this.user.lstCategory),
    }, {
      validator: MustMatch('password', 'passwordConfirm')
    });
  }
///html
<form [formGroup]="editUserForm" (ngSubmit)="onSave()" >
    <table *ngIf="user">
...
                  <mat-selection-list formControlName="lstCat" class="col-md-12 col-sm-12">
                    <mat-list-option  *ngFor="let cat of cbxCategory" [value]="cat">
                      {{cat.libelle}}
                    </mat-list-option>
...    
   </table>
  </form>

如果您使用 Angular 材料 7+,请在 mat-selection-list 上使用compareWith输入属性,它将 function 作为输入值。

此 Function 用于在确定哪些选项应显示为选中时将选项与所选值进行比较

组件.html

<form [formGroup]="clientForm">
  <h1>
    FormControl Value
  </h1>

  <pre>
    {{ clientForm.get('myOtherControl').value | json }}
  </pre>

  <mat-selection-list *ngIf="listValue" formControlName="myOtherControl" [compareWith]="compare" >
    <mat-list-option *ngFor="let list of listValue" [value]="list" multiple>{{list.name}}</mat-list-option>
  </mat-selection-list>
</form> 

组件.ts

 compare(c1: {id: string}, c2: {id: string}) {
    return c1?.id === c2?.id;
  }

分叉的工作示例

我认为你在错误的地方调用 initForm 方法。应该在 categoryService.getAllCategory() 订阅中移动 initForm 方法,或者如果对先前的调用有依赖关系,你可以使用 pipe 运算符

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM