首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在ControlValueAccessor的自定义实现中访问“ControlValueAccessor”选项?

如何在ControlValueAccessor的自定义实现中访问“ControlValueAccessor”选项?
EN

Stack Overflow用户
提问于 2019-10-29 11:48:10
回答 1查看 758关注 0票数 3

我必须按照下面的格式

代码语言:javascript
复制
form = new FormGroup({
   title: new FormControl(null, {updateOn: 'blur'}),
})

对于标题输入,我创建了一个实现ControlValueAccessor的自定义控件ControlValueAccessor。如何访问此控件中的updateOn选项?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-10-29 20:10:23

在谷歌搜索之后,我找到了两个解决方案:

解决方案1:

注意,没有NG_VALUE_ACCESSOR提供程序。

代码语言:javascript
复制
@Component({
    selector: 'app-my-input',
    templateUrl: './my-input.component.html',
    styles: [],
})  
export class MyInputComponent implements OnInit, ControlValueAccessor, AfterViewInit {
    onChange: (_: any) => void;
    onTouched: () => void;
    isDisabled: boolean;
    value: string;

    constructor(private ngControl: NgControl) {
        ngControl.valueAccessor = this;
    }

    ngOnInit() {
        console.log('Update On: ', this.ngControl.control.updateOn);
    }
}

解决方案2。

代码语言:javascript
复制
@Component({
    selector: 'app-my-input',
    templateUrl: './my-input.component.html',
    styles: [],
    providers: [
    {
        provide: NG_VALUE_ACCESSOR,
        useExisting: forwardRef(() => MyInputComponent),
        multi: true,
    },
    ],
})
export class MyInputComponent implements OnInit, ControlValueAccessor, AfterViewInit {
    onChange: (_: any) => void;
    onTouched: () => void;
    isDisabled: boolean;
    value: string;

    ngControl: NgControl;

    constructor(private inj: Injector) {
    }

    ngOnInit() {
        this.ngControl = this.inj.get(NgControl);
    }

    ngAfterViewInit(): void {
        console.log('Update on:', this.ngControl.control.updateOn);
    }
} 
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58606860

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档