11
votes

Angular 2 has a 'safe navigation operator' that allows template references to potentially undefined child properties in your components.

Is there any way to use this with dynamic properties and bracket notation? e.g.,

<input [type]="text" [ngModel]="formValues?[control]">

Where control is another variable from my component telling the template which form value to use and formValues is loaded async so could potentially be null.

1
This is basically nothing to go on, please share more code so we can help :) - AJT82
@AJT_82, thanks for commenting. The code in question doesn't really matter it's more of a generic technique. Angular 1 was null safe for template references. Rather than use that behavior Angular 2 has the 'safe navigation operator'. But is there a way to use that with variable property names? I feel like I must be missing something obvious. - Roy Reiss
Asked because since not knowing what formValues?[control] is supposed to REALLY do or contains. So hard to say if it could work. Something like someObj?.someProperty I do understand what is doing exactly. Hmm, might *ngIf work for you in this case, to check that there is value before rendering? <input *ngIf="formValues[control]" ... /> as said, not really knowing what is going on with that, hard to help further. - AJT82
@AJT_82, here's a plnk plnkr.co/edit/TeGqrnZJA9zADN6NhYzB?p=preview I figured ngIf might be the only way. Makes the safe navigation operator kind of a poor replacement for the way Ng1 handled this :) (though it's better in lots of other ways) - Roy Reiss
Thanks for plunker. With this it seems to work fine with the ngIf, was this something you were looking for? plnkr.co/edit/KGD9QP4IZyA2CshehMrr?p=preview - AJT82

1 Answers

1
votes

I think that you can't, but this is what I'm using, simpler than ngif but empty string and 0 will not do what is after the && :

<input [type]="text" [ngModel]="formValues && formValues[control]">