gpt4 book ai didi

angular - 为什么 Angular 不在我的 ControlValueAccessor 实现中调用 registerOnChange?

转载 作者:太空狗 更新时间:2023-10-29 17:33:30 25 4
gpt4 key购买 nike

我正在尝试在 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 是 native 控件和 Angular 的表单控件之间的中介:

enter image description here

可以通过应用 NgModel 指令自动创建 Angular 表单控件,如下所示:

<editor-clause ngModel *ngFor="let clause of clauses" [clause]="clause"></editor-clause>

或者手动在组件中然后使用formControl指令绑定(bind)到一个控件:

export class EditorClauseComponent ... {
myControl = new FormControl();

模板:

<editor-clause [formControl]="myControl" *ngFor="let clause of clauses" [clause]="clause"></editor-clause>

关于angular - 为什么 Angular 不在我的 ControlValueAccessor 实现中调用 registerOnChange?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47941572/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com