NgModel value is always null and change event never triggered. But value has changed.
See original GitHub issueBug Report
Affected Package
@angular/forms
Description
The value of NgModel
is always null
and no change events are fired. But the NgModel
itself works. In browser console I see some private keys with the lastValue which is correct and a proof for me that this is the correct NgModel link to the input element. (__ngContext__
see console).
Maybe my expectation is completely wrong. Either this is a bug or a lack of docs, etc. But we can handle an unexpected behavior as a bug. This results in one questions.
How to access (read / write) the NgModel value of the host element (e.g. input) from a directive?
There are some threads on Stackoverflow, etc. But nothing helps. … I’ve tried everything I can’t get this to life. Please teach me if I’m wrong. But this is a bug or a lack in my opinion.
Btw. the <input>
element is just an example. I don’t want to read the native value from this element. For example: Some frameworks wraps the native input element in a not accessible scope. So I want to get the current NgModel value. This has nothing to do with <input>
. It’s just about the NgModel.
Minimal Reproduction
import { Directive, HostListener } from '@angular/core';
import { NgModel } from '@angular/forms';
@Directive({ selector: 'input[appSome]', providers: [NgModel] })
export class SomeDirective {
constructor(private ngModel: NgModel) {}
// Or other events....
@HostListener('ngModelChange')
inputChanged() {
console.log('Changed:', this.ngModel.value);
// Result: Changed: null (always)
}
}
Your Environment
Angular Version:
Your global Angular CLI version (12.0.2) is greater than your local version (11.0.2).
The local Angular CLI version is used.
Angular CLI: 11.0.2
Node: 14.15.1
OS: win32 x64
Angular: 11.0.2
... animations, cli, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router
Ivy Workspace: Yes
Package Version
---------------------------------------------------------
@angular-devkit/architect 0.1100.2
@angular-devkit/build-angular 0.1100.2
@angular-devkit/core 11.0.2
@angular-devkit/schematics 11.0.2
@schematics/angular 11.0.2
@schematics/update 0.1100.2
rxjs 6.6.3
typescript 4.0.5
Issue Analytics
- State:
- Created 2 years ago
- Comments:6 (3 by maintainers)
Top GitHub Comments
Yes I was just about to say the same as @jnizet: https://stackblitz.com/edit/angular-ivy-ngmodel-directive-issue-rf2pfy?file=src%2Fapp%2Fsome.directive.ts
Adding the
NgModel
to the providers actually creates a newNgModel
“service” on the injector for this directive, which shadows thengModel
directive on the host element.Closing because this works as expected.
I tested that without the
providers: [NgModel]
that you have in your stackblitz. If you remove it, everything works fine, including usingngModel.value
.