Can someone help explain why my [(ngModel)] is not displaying my input? So I have a @Input receivedCode: number in my .ts file and in my html file I have <input matInput type="text" numbersOnly="true" class="departmentCodeInput" [(ngModel)]="recievedCode" data-testid="departmentCode-input"> and everything works fine however I'm currently trying to write test for the component and in doing so read that it is bad practice to modify inputs received from parent components. So I defined and initialized a new variable code: number = this.receivedCode in ngOnInit and then setting [(ngModel)] = "code" however now the code is not displaying at all whereas previously it was.
#ngModel not displaying properly
6 messages · Page 1 of 1 (latest)
You should use your input in input using [ngModel]=receivedCode. Then you can use (ngModel)=receivedCodeChange.emit($event).
And of course you need to define receivedCodeChange as output.
Your code above doesn't work because you bind your input value once, once component have initialized
Therefore when it's value change, it is not reflected in your component
Thanks I ended up seeing something on stackoverflow that suggested ngOnChanges() { if (this.receivedCode !== undefined) { this.code = this.receivedCode; } } and this seems to have also worked
Yeah, this solution will work. Although, you should consider that ngOnChanges runs every detect cycle, so it is not as performant as using just input and output