Search code examples
javascripthtmlangularangular-ngmodelangular-ngmodelchange

How does ngModelChange works without providing model name in ngModel directive


How does ngModelChange() works?

(ngModelChange) is the @Output of ngModel directive. It fires when the model changes. You cannot use this event without ngModel directive

but I am not sure, how does(ngModelChange) it works, if I am use ngModelChange() event, even i am not providing model name to ngModel.

<input #gb type="text" pInputText class="ui-widget ui-text" **ngModel**  
 (ngModelChange)="functionName($event)">

Solution

  • Yes, ngModelChange() work without providing model name to ngModel.

    cause of this happen, (ngModelChange) is the @Output of ngModel directive. when insert some value in input that time emitEvent is become true which is by default false (so it not fire page load on initial time).

    _this.updateValueAndValidity({ emitEvent: false });

    you can find at \@angular\forms\esm5\forms.js ► line no 3850

    If emitEvent is true, this change will cause a valueChanges event on the FormControl to be emitted. This defaults to true (as it falls through to updateValueAndValidity).

    If emitViewToModelChange is true, an ngModelChange event will be fired to update the model. This is the default behavior if emitViewToModelChange is not specified.

    If emitModelToViewChange is true, the view will be notified about the new value via an onChange event.

    now question is that why get same value in $event which is inserted in input instead of ture, that cause

    FormControl.prototype.setValue = /**

    function (value, options) {
            var _this = this;
            if (options === void 0) { options = {}; }
            (/** @type {?} */ (this)).value = this._pendingValue = value;
            if (this._onChange.length && options.emitModelToViewChange !== false) {
                this._onChange.forEach(function (changeFn) { return changeFn(_this.value, options.emitViewToModelChange !== false); });
            }
            this.updateValueAndValidity(options);
        };
    

    same file line no 3911 to 3919