【问题标题】:Use a custom component to alter the value of a formControl使用自定义组件更改 formControl 的值
【发布时间】:2020-03-25 14:59:55
【问题描述】:

我正在我的 Angular 应用程序中构建一个响应式表单。我有一个我构建的小型可重用组件,我想使用该组件来更改我的 formGroup 中一个 formControls 的值。但是我似乎无法正确连接它。

像使用matInputmat-slide-toggle 那样简单地使用formControlName 似乎并没有同样的效果。

我的可重用组件正在使用其自身的输入,无论如何我可以将它链接到我组中的 formControl 吗?

可重用组件的使用

<app-tenant-picker 
    (selectedTenant)="changeSelectedTenant($event)"
    formControlName="tenant">
</app-tenant-picker>

可重用组件html

<mat-form-field class="full-width">
        <mat-label>{{ label }}</mat-label>
        <mat-icon class="search-icon" matSuffix>keyboard_arrow_down</mat-icon>
        <input type="text" matInput [formControl]="tenantListFormControl" [matAutocomplete]="auto"
               autocomplete="off">
        <mat-autocomplete autoActiveFirstOption #auto="matAutocomplete"
                          [displayWith]="displayTenantNameInAutocomplete"
                                              (optionSelected)="emitTenant($event)">
            <mat-option *ngFor="let tenant of filteredTenantList$ | async" [value]="tenant">
                {{tenant.name}}
            </mat-option>
        </mat-autocomplete>
    </mat-form-field>

(selectedTenant) 只是一个简单的 eventEmitter:@Output() selectedTenant = new EventEmitter&lt;Tenant&gt;();

表单组

this.form = this._formBuilder.group({
        name: new FormControl('', [Validators.required]),
        comment: new FormControl(''),
        tenant: new FormControl('', [Validators.required]),
        sources: new FormArray([]),
        include: this.includeLocation,
        location: new FormControl('', [Validators.required]),
        locationComment: new FormControl('')
      });

其他

selectedTenant: Tenant;
...
changeSelectedTenant(tenant: Tenant) {
    this.selectedTenant = tenant;
    console.log("ST: ",this.selectedTenant);
  }

如果我还有什么遗漏的,请告诉我,我会将其添加到问题中。

【问题讨论】:

  • 我认为你需要为你的自定义控件/组件写一个ControlValueAccessor。 Angular 为标准控件提供了这些。

标签: angular


【解决方案1】:

你需要在你的自定义组件上实现ControlValueAccessor

阅读更多关于它的信息herehere

【讨论】:

    猜你喜欢
    • 2021-10-10
    • 2020-04-18
    • 2021-01-25
    • 2017-11-27
    • 1970-01-01
    • 2021-11-11
    • 2020-09-15
    • 1970-01-01
    • 2021-10-29
    相关资源
    最近更新 更多