如何在Angular的ControlValueAccessor的自定义实现中访问'updateOn'选项?

问题描述 投票:0回答:1

我必须遵循以下形式

form = new FormGroup({
   title: new FormControl(null, {updateOn: 'blur'}),
})

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

angular angular-reactive-forms
1个回答
0
投票

经过一番谷歌搜索后,我找到了两种解决方案:

解决方案1:

注意,没有NG_VALUE_ACCESSOR提供程序。

@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。

@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);
    }
} 
© www.soinside.com 2019 - 2024. All rights reserved.