在Angular Material mat-select上创建自定义组件

3

我希望在 Angular Material mat-select 的基础上创建一个自定义组件。

这个自定义组件应该支持响应式表单和非响应式表单两种形式。

自定义组件需要接收以下输入:

  • @Input() group: FormGroup;
  • @Input() controlName: string;

自定义组件的 HTML 如下:

<mat-form-field [formGroup]="group">
  <mat-select placeholder="Favorite food" [formControlName]="controlName">
    <mat-option *ngFor="let food of foods" [value]="food.value">
      {{food.viewValue}}
    </mat-option>
  </mat-select>
</mat-form-field>

如果我传递组和控件名称,那么这个组件可以很好地工作。 但是,当我想在没有响应式表单的情况下使用相同的组件时,就会出现错误:"formGroup expects a FormGroup instance. Please pass one in"。

<!-- With Reactive Form -->
<app-custom-dropdown [group]="form" [controlName]="'foods'"></app-custom-dropdown>

<!-- Without Reactive Form -->
<app-custom-dropdown></app-custom-dropdown>

我的问题是如何在使用响应式表单时支持自定义组件,在其他情况下不使用响应式表单。 stackblitz示例

为什么你不需要响应式表单?这个组件有什么用途? - Niladri
这个自定义组件是一个下拉菜单,包含了我在一个大项目中使用的操作系统类型。在该项目中,我们有时使用模板驱动表单,有时使用响应式表单。 - ofir fridman
1个回答

1
当您使用模板表单并像这样调用您的组件时:
<app-custom-dropdown></app-custom-dropdown>

你没有传递 formGroup,所以在你的 app-custom-dropdown 组件中,模板中传递的 @Input() group 将是未定义的。

<mat-form-field [formGroup]="group">

所以在这里,您需要添加一个条件来避免传递未定义的group更新 这是可能的其中一个例子。
<ng-container *ngTemplateOutlet='group ? reactive : template'>
</ng-container>

<ng-template #reactive>
  <mat-form-field [formGroup]="group">
    <mat-select placeholder="Favorite food" [formControlName]="controlName">
      <mat-option *ngFor="let food of foods" [value]="food.value">
        {{food.viewValue}}
      </mat-option>
    </mat-select>
  </mat-form-field>
</ng-template>

<ng-template #template>
  <mat-form-field>
    <mat-select placeholder="Favorite food" >
      <mat-option *ngFor="let food of foods" [value]="food.value">
        {{food.viewValue}}
      </mat-option>
    </mat-select>
  </mat-form-field>
</ng-template>

你如何处理这个条件? - ofir fridman
这取决于您如何在<mat-form-field>组件中使用formGroup。 - Artyom Amiryan
同时,您应该在mat-form-field和mat-select组件中删除formControlName并进行templateRef操作,这有点复杂。 - Artyom Amiryan
https://stackblitz.com/edit/angular-b8qgag-sttnkj 我在这里更新了链接,请再次检查,之前的版本没有保存。 - Artyom Amiryan
我看了你的解决方案,这正是我在做的项目中所用的方式。我不喜欢这个解决方案的原因是我必须维护两个模板。但无论如何,感谢你的帮助。 - ofir fridman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接