【发布时间】:2018-03-26 09:00:20
【问题描述】:
我已经实现了以下组件。它按预期工作和表现。尽管如此,由于ControlValueAccessor 的实现对我来说是新的,我不得不follow a blog 而不了解一些部分的更深层次的细节。所以这是一种“它有效但为什么?!”的情况。
@Component({ selector: ..., templateUrl: ..., styleUrls: ...,
providers: [{ provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => InputTextComponent),
multi: true }]
})
export class InputComponent implements ControlValueAccessor {
constructor() { }
@Input() info: string;
onChange: any = () => { }
onTouch: any = () => { }
writeValue(input: any): void {
this.info.value = input;
// this.onChange(input);
// this.onTouch();
}
registerOnChange(_: any): void { this.onChange = _; }
registerOnTouched(_: any): void { this.onTouch = _; }
setDisabledState?(state: boolean): void { }
onEdit(value: string): void { this.onChange(value); }
}
当我让它工作时,我注释掉了writeValue(...) 方法的第二行和第三行,据我所知,没有任何问题。 other blogs 也一直建议这些调用,所以我相信忽略它们是不合适的。不过,我不相信魔法,更喜欢有具体的做事理由。
为什么在writeValue(...) 中执行对onChange(...) 和onTouch(...) 的调用很重要?会出现什么问题以及在什么情况下会出现问题?
作为一个支线任务,我还尝试注释掉 the other methods 并发现当我删除 setDisabledState(...) 时我无法说出任何事情。什么时候可以预期会引起问题?它真的需要实现吗(我见过括号前后都有问号的版本,参数如下:setDisabledState?(state: boolean): void { },但也像这样:setDisabledState(state: boolean)?: void { })。
【问题讨论】:
-
你是如何使用这个组件的?
-
Why is it important to execute the call to onChange(...) and onTouch(...) in writeValue(...)?你在哪里看到的? -
@yurzui,这里大概指的是these
-
@AngularInDepth.com 我想他指的是这个take.ms/IGcPJ
标签: angular typescript custom-component