我正在使用Range6开发一个web应用程序。是否可以引用模板中使用的组件(本例中是我的custom-component),如本例所示:
<custom-component #select
name="name1"
title="Select first option"
[(ngModel)]="select.value"
>
</custom-component>如您所见,[(ngModel)]属性具有值select.value。这个值是CustomComponent的一个属性(总是需要连接到ngModel)。为了引用它,我使用了#select,但我想知道是否有其他方式或关键字允许我使用value属性,而无需在模板中的自定义组件的每次使用中使用#select装饰器。
发布于 2018-12-05 15:44:39
您可以在自定义组件上使用ngModel和ControlValueAccessor。
在custom-componen类中扩展ControlValueAccessor
export class CustomComponent implements , ControlValueAccessor {
onChange = (val: string) => { };
onTouched = () => { };
writeValue(val: string): void {
// value passed from parent throug ngModel will come under this funtion
}
registerOnChange(fn: (val: string) => void): void {
this.onChange = fn;
}
registerOnTouched(fn: () => void): void {
this.onTouched = fn;
}
ngOnInit() {
}
// If you want to emit value to parent use the onChange function
myEmitFunction(){
this.onChange("value u want to emit")
}
}https://stackoverflow.com/questions/53635849
复制相似问题