Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2019
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.68 KB | None | 0 0
  1. @Directive({
  2. selector: '[ngModel]:not([formControlName]):not([formControl])',
  3. providers: [formControlBinding],
  4. exportAs: 'ngModel'
  5. })
  6. export class NgModel extends NgControl implements OnChanges,
  7. OnDestroy {
  8. public readonly control: FormControl = new FormControl();
  9. /** @internal */
  10. _registered = false;
  11.  
  12. /**
  13. * @description
  14. * Internal reference to the view model value.
  15. */
  16. viewModel: any;
  17.  
  18. @Input() name !: string;
  19.  
  20. @Input('disabled') isDisabled !: boolean;
  21.  
  22. /**
  23. * @description
  24. * Tracks the value bound to this directive.
  25. */
  26. // 根据注释,这里即指令要跟踪的值
  27. @Input('ngModel') model: any;
  28.  
  29. @Input('ngModelOptions')
  30. options !: {name?: string, standalone?: boolean, updateOn?: FormHooks};
  31.  
  32. @Output('ngModelChange') update = new EventEmitter();
  33.  
  34. constructor(@Optional() @Host() parent: ControlContainer,
  35. @Optional() @Self() @Inject(NG_VALIDATORS) validators: Array<Validator|ValidatorFn>,
  36. @Optional() @Self() @Inject(NG_ASYNC_VALIDATORS) asyncValidators: Array<AsyncValidator|AsyncValidatorFn>,
  37. @Optional() @Self() @Inject(NG_VALUE_ACCESSOR)
  38. valueAccessors: ControlValueAccessor[]) {
  39. super();
  40. this._parent = parent;
  41. this._rawValidators = validators || [];
  42. this._rawAsyncValidators = asyncValidators || [];
  43. this.valueAccessor = selectValueAccessor(this, valueAccessors);
  44. }
  45.  
  46. /**
  47. * @description
  48. * A lifecycle method called when the directive's inputs change. For internal use
  49. * only.
  50. *
  51. * @param changes A object of key/value pairs for the set of changed inputs.
  52. */
  53. // 定义 ngOnChange( Angular 对 change 事件的封装) 的 handler
  54. ngOnChanges(changes: SimpleChanges) {
  55. this._checkForErrors();
  56. if (!this._registered) this._setUpControl();
  57. if ('isDisabled' in changes) {
  58. this._updateDisabled(changes);
  59. }
  60.  
  61. if (isPropertyUpdated(changes, this.viewModel)) {
  62. // 调用 _updateValue 来应用新的值
  63. this._updateValue(this.model);
  64. this.viewModel = this.model;
  65. }
  66. }
  67.  
  68. ngOnDestroy(): void { this.formDirective && this.formDirective.removeControl(this); }
  69.  
  70. get path(): string[] {
  71. return this._parent ? controlPath(this.name, this._parent) : [this.name];
  72. }
  73.  
  74. get formDirective(): any { return this._parent ? this._parent.formDirective : null; }
  75.  
  76. get validator(): ValidatorFn|null { return composeValidators(this._rawValidators); }
  77.  
  78. get asyncValidator(): AsyncValidatorFn|null {
  79. return composeAsyncValidators(this._rawAsyncValidators);
  80. }
  81.  
  82. viewToModelUpdate(newValue: any): void {
  83. this.viewModel = newValue;
  84. this.update.emit(newValue);
  85. }
  86.  
  87. private _setUpControl(): void {
  88. this._setUpdateStrategy();
  89. this._isStandalone() ? this._setUpStandalone() :
  90. this.formDirective.addControl(this);
  91. this._registered = true;
  92. }
  93.  
  94. private _setUpdateStrategy(): void {
  95. if (this.options && this.options.updateOn != null) {
  96. this.control._updateOn = this.options.updateOn;
  97. }
  98. }
  99.  
  100. private _isStandalone(): boolean {
  101. return !this._parent || !!(this.options && this.options.standalone);
  102. }
  103.  
  104. private _setUpStandalone(): void {
  105. setUpControl(this.control, this);
  106. this.control.updateValueAndValidity({emitEvent: false});
  107. }
  108.  
  109. private _checkForErrors(): void {
  110. if (!this._isStandalone()) {
  111. this._checkParentType();
  112. }
  113. this._checkName();
  114. }
  115.  
  116. private _checkParentType(): void {
  117. if (!(this._parent instanceof NgModelGroup) &&
  118. this._parent instanceof AbstractFormGroupDirective) {
  119. TemplateDrivenErrors.formGroupNameException();
  120. } else if (
  121. !(this._parent instanceof NgModelGroup) && !(this._parent instanceof NgForm)) {
  122. TemplateDrivenErrors.modelParentException();
  123. }
  124. }
  125.  
  126. private _checkName(): void {
  127. if (this.options && this.options.name) this.name = this.options.name;
  128.  
  129. if (!this._isStandalone() && !this.name) {
  130. TemplateDrivenErrors.missingNameException();
  131. }
  132. }
  133.  
  134. // 用 control.setValue 给绑定的属性赋值
  135. private _updateValue(value: any): void {
  136. resolvedPromise.then(
  137. () => { this.control.setValue(value, {emitViewToModelChange: false}); });
  138. }
  139.  
  140. private _updateDisabled(changes: SimpleChanges) {
  141. const disabledValue = changes['isDisabled'].currentValue;
  142.  
  143. const isDisabled =
  144. disabledValue === '' || (disabledValue && disabledValue !== 'false');
  145.  
  146. resolvedPromise.then(() => {
  147. if (isDisabled && !this.control.disabled) {
  148. this.control.disable();
  149. } else if (!isDisabled && this.control.disabled) {
  150. this.control.enable();
  151. }
  152. });
  153. }
  154. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement