💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
## FormControl 追踪单个控件的值和验证状态。 `FormControl`同`FormGroup`及`FormArray`一同构成Angular表单3大基础功能模块。 ### 使用方式 实例化`FormControl`,传递一个初始化值作为第一个参数。 ```typescript const ctrl = new FormControl('some value'); console.log(ctrl.value); // 'some value' ``` 也可以在实例化的时候初始化一个状态对象,包括初始值和当前控件是否被禁用的状态。在使用对象方式初始化值的时候必须同时包含`value`和`disabled`两个属性,不能只指定`value`值。 ```typescript const ctrl = new FormControl({value: 'n/a', disabled: true}); console.log(ctrl.value); // 'n/a' console.log(ctrl.status); // 'DISABLED' ``` 在当前控件中包含一个同步验证验证器(一组同步验证器),请传入第二个参数。同样,异步验证器也可以,但需要作为第三个参数单独传入。 ```typescript const ctrl = new FormControl('', Validators.required); console.log(ctrl.value); // '' console.log(ctrl.status); // 'INVALID' ``` ### Class ```typescript class FormControl { constructor(formState?: any, validator?: ValidatorFn|ValidatorFn[], asyncValidator?: AsyncValidatorFn|AsyncValidatorFn[]) setValue(value: any, {onlySelf, emitEvent, emitModelToViewChange, emitViewToModelChange}?: {?: boolean,?: boolean,?: boolean,?: boolean}) : void patchValue(value: any, options?: {?: boolean,?: boolean,?: boolean,?: boolean}) : void reset(formState?: any, {onlySelf}?: {onlySelf?: boolean}) : void registerOnChange(fn: Function) : void registerOnDisabledChange(fn: (isDisabled: boolean) => void) : void } ``` ### 属性 - setValue(value: `any`, {onlySelf, emitEvent, emitModelToViewChange, emitViewToModelChange}?: { onlySelf?: `boolean`, emitEvent?: `boolean`, emitModelToViewChange?: `boolean`, emitViewToModelChange?: `boolean` }) : `void` 设置控件的`value`值。 如果`onlySelf`为`true`,当前操作只会影响控件本身的验证状态,不会影响父节点。默认为`false`。 如果 `emitEvent`为`true`,当前操作会发送一个`valueChanges`事件。默认为`true` (as it falls through to `updateValueAndValidity`) 如果`emitModelToViewChange`为`true`,当前操作会发送`onChange`事件通知视图。默认为`true` 如果`emitViewToModelChange`为`true`,会触发`ngModelChange`事件更新模型。默认为`true`。 - patchValue(value: `any`, options?: { onlySelf?: `boolean`, emitEvent?: `boolean`, emitModelToViewChange?: `boolean`, emitViewToModelChange?: `boolean` }) : `void` 功能同`setValue`,目的是和`FormGroup`和`FormArray`保持一质,但功能不同。 - reset(formState?: `any`, {onlySelf}?: {onlySelf?: `boolean`}) : `void` You can also reset to a specific form state by passing through a standalone value or a form state object that contains both a value and a disabled state (these are the only two properties that cannot be calculated). ```typescript this.control.reset('Nancy'); console.log(this.control.value); // 'Nancy' ``` 或者 ```typescript this.control.reset({value: 'Nancy', disabled: true}); console.log(this.control.value); // 'Nancy' console.log(this.control.status); // 'DISABLED' ``` - registerOnChange(fn: `Function`) : `void` 注册一个监听变化的事件监听器。 - registerOnDisabledChange(fn: (isDisabled: `boolean`) => `void`) : `void` 注册一个监听控件禁用状态变化的事件监听器。