2016-06-23 09:47:54 -07:00
|
|
|
/**
|
|
|
|
|
* @license
|
|
|
|
|
* Copyright Google Inc. All Rights Reserved.
|
|
|
|
|
*
|
|
|
|
|
* Use of this source code is governed by an MIT-style license that can be
|
|
|
|
|
* found in the LICENSE file at https://angular.io/license
|
|
|
|
|
*/
|
|
|
|
|
|
2016-06-08 15:36:24 -07:00
|
|
|
import {Directive, ElementRef, Renderer, forwardRef} from '@angular/core';
|
2016-06-08 16:38:52 -07:00
|
|
|
|
|
|
|
|
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from './control_value_accessor';
|
2016-06-08 15:36:24 -07:00
|
|
|
|
2016-07-30 19:18:14 -07:00
|
|
|
export const DEFAULT_VALUE_ACCESSOR: any = {
|
|
|
|
|
provide: NG_VALUE_ACCESSOR,
|
|
|
|
|
useExisting: forwardRef(() => DefaultValueAccessor),
|
|
|
|
|
multi: true
|
|
|
|
|
};
|
2016-06-08 15:36:24 -07:00
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* The default accessor for writing a value and listening to changes that is used by the
|
2016-06-12 13:17:07 -07:00
|
|
|
* {@link NgModel}, {@link FormControlDirective}, and {@link FormControlName} directives.
|
2016-06-08 15:36:24 -07:00
|
|
|
*
|
|
|
|
|
* ### Example
|
|
|
|
|
* ```
|
2016-06-12 13:17:07 -07:00
|
|
|
* <input type="text" name="searchQuery" ngModel>
|
2016-06-08 15:36:24 -07:00
|
|
|
* ```
|
|
|
|
|
*
|
2016-08-17 07:44:39 -07:00
|
|
|
* @stable
|
2016-06-08 15:36:24 -07:00
|
|
|
*/
|
|
|
|
|
@Directive({
|
|
|
|
|
selector:
|
2016-06-12 13:17:07 -07:00
|
|
|
'input:not([type=checkbox])[formControlName],textarea[formControlName],input:not([type=checkbox])[formControl],textarea[formControl],input:not([type=checkbox])[ngModel],textarea[ngModel],[ngDefaultControl]',
|
2016-06-08 15:36:24 -07:00
|
|
|
// TODO: vsavkin replace the above selector with the one below it once
|
|
|
|
|
// https://github.com/angular/angular/issues/3011 is implemented
|
|
|
|
|
// selector: '[ngControl],[ngModel],[ngFormControl]',
|
|
|
|
|
host: {'(input)': 'onChange($event.target.value)', '(blur)': 'onTouched()'},
|
|
|
|
|
providers: [DEFAULT_VALUE_ACCESSOR]
|
|
|
|
|
})
|
|
|
|
|
export class DefaultValueAccessor implements ControlValueAccessor {
|
|
|
|
|
onChange = (_: any) => {};
|
|
|
|
|
onTouched = () => {};
|
|
|
|
|
|
|
|
|
|
constructor(private _renderer: Renderer, private _elementRef: ElementRef) {}
|
|
|
|
|
|
|
|
|
|
writeValue(value: any): void {
|
2016-11-11 10:47:34 -08:00
|
|
|
const normalizedValue = value == null ? '' : value;
|
2016-06-08 15:36:24 -07:00
|
|
|
this._renderer.setElementProperty(this._elementRef.nativeElement, 'value', normalizedValue);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
registerOnChange(fn: (_: any) => void): void { this.onChange = fn; }
|
|
|
|
|
registerOnTouched(fn: () => void): void { this.onTouched = fn; }
|
2016-08-24 16:58:43 -07:00
|
|
|
|
|
|
|
|
setDisabledState(isDisabled: boolean): void {
|
|
|
|
|
this._renderer.setElementProperty(this._elementRef.nativeElement, 'disabled', isDisabled);
|
|
|
|
|
}
|
2016-06-08 15:36:24 -07:00
|
|
|
}
|