Search code examples
angularangular-ng-ifngmodelangular-ngmodelchange

Set undefined value using *ngIf and ngModelChange


I am using (ngModelChange) with several attribute but one of its attribute can be null for some entry. For now the only solution I have found is to duplicate the input with *ngIf condition to check if attribute is not null.

<input *ngIf="!member.instrument" [(ngModel)]="member.firstname" (ngModelChange)="updateField(member.key,noinstrument,member.firstname)">
<input *ngIf="member.instrument"[(ngModel)]="member.firstname" (ngModelChange)="updateField(member.key,member.instrument.key,member.firstname)">

If I don't do this I have the following error calling the ngModelChange :

ERROR TypeError: Cannot read property 'member.instrument.key' of undefined

I'm sure there is a way to do this with only one input field... Maybe setting the member.instrument.key to null when it's not defined?


Solution

  • Try something like this

    updateField(member.key,
                member.instrument?member.instrument.key:undefined,
                member.firstname)"