我正在尝试在Angular 4中的模板驱动器表单中实现自定义表单控件组件。因为我希望它与父表单很好地集成,我试图将其实现为ControlValueAccessor。我遵循了我能找到的指南,但Angular没有合作。根据文档,它应该调用我的registerOnChange()
实现,但它没有。这是为什么?
/* editor-clause.component.ts */
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { QueryClause } from '../../../../models/query-clause';
import { Input, Component, EventEmitter, Output } from '@angular/core';
@Component({
moduleId: module.id,
providers: [{
provide: NG_VALUE_ACCESSOR,
useExisting: EditorClauseComponent,
multi: true,
}],
selector: 'editor-clause',
templateUrl: './editor-clause.component.html',
styleUrls: ['./editor-clause.component.css']
})
export class EditorClauseComponent implements ControlValueAccessor {
@Input('clause') clause: QueryClause;
parentOnChange: any;
writeValue(_obj: any): void {
return;
}
registerOnChange(fn: any): void {
// This never gets printed and I don't know why
console.log('Registering parent change tracking');
this.parentOnChange = () => {
console.log('Saw a change. Invoking parent function');
fn();
};
}
registerOnTouched(_fn: any): void {
return;
}
}
包含父表单看起来像:
<form #queryBuilderForm="ngForm">
<p>Form instructions here</p>
<editor-clause *ngFor="let clause of clauses" [clause]="clause"></editor-clause>
<button (click)="addClause()" id="add-query-clause-button">Add clause</button>
</form>
正如文章Never again be confused when implementing ControlValueAccessor in Angular forms中所解释的那样,ControlValueAccessor
是本机控件和Angular的表单控件之间的中介:
可以通过应用NgModel
指令自动创建Angular表单控件,如下所示:
<editor-clause ngModel *ngFor="let clause of clauses" [clause]="clause"></editor-clause>
或者在组件中手动,然后使用formControl
指令绑定到控件:
export class EditorClauseComponent ... {
myControl = new FormControl();
模板:
<editor-clause formControl="myControl" *ngFor="let clause of clauses" [clause]="clause"></editor-clause>