【发布时间】:2020-03-25 14:59:55
【问题描述】:
我正在我的 Angular 应用程序中构建一个响应式表单。我有一个我构建的小型可重用组件,我想使用该组件来更改我的 formGroup 中一个 formControls 的值。但是我似乎无法正确连接它。
像使用matInput 或mat-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<Tenant>();
表单组
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