【发布时间】:2019-04-13 13:11:46
【问题描述】:
使用implements ControlValueAccessor开发的InputFieldComponent组件
constructor(public cd: ChangeDetectorRef) {
}
onTouchedCallback = () => { };
onChangeCallback: any = () => { };
// register a handler that should be fired when something in the view has changed
registerOnChange(fn: any): void {
this.onChangeCallback = fn;
}
// registers a handler specifically for when a control receives a touch event.
registerOnTouched(fn: any): void {
this.onTouchedCallback = fn;
}
// writes new values from the form model into the view or any DOM property
writeValue(value: string): void {
if (value !== this.innerValue) {
this.innerValue = value;
}
}
// textbox input change
onChange(event: any): void {
this.onChangeCallback(event.target.value);
}
像这样动态添加。
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(InputFieldComponent);
const newComponent = container.createComponent(componentFactory);
设置
form.addControl("firstname",
new FormControl("Some TEXT ", Validators.required));
newComponent.instance.formControlName = "firstname"
试图通过写下一行来触发writeValue:
newComponent.instance.cd.detectChanges();
但没有运气,如何解决这个问题?我想在文本框值中看到“一些文本”。
通常如果我使用这个组件 html,它可以正常工作。
这里是我尝试过的 stackblitz 链接:-
https://stackblitz.com/edit/angular-custom-input-init-value-d34jls
【问题讨论】:
-
你能创建stackblitz吗
-
是的,我正在创建 stackblitz
-
@Chellappan - 我已经更新了 stackblitz,在此先感谢。
-
你为什么要这样?
-
因为我们有很多组件,不想在html中使用ngswitch,你有什么建议?
标签: angular angular6 angular-reactive-forms