Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 to show string/key used in ngModel dynamically?

I am new to angular2. I have been trying to find the possible ways to show the string which is used for binding in [(ngModel)] dynamically. My objective to show the binding key which is used in HTML Elements in DOM itself based on Url param. Since my application is huge this will be more productive for development.

I need to show every ngModel string/key which is placed under any div wrapper using 'Directive'. Let say 'showModelKey' will be used to identify the elements placed under Div wrapper.

<div class='content-wrapper' showModelKey>
 <input [(ngModel)]="myFirstName" name="first_name">
  <!-- here myFirstName is ngModel string/key -->
....
 <textarea[(ngModel)]="commentModel" name="comment"></textarea>
 </div>

Here showModelKey should find the fields used under div wrapper and add another directive (if needed) to show the key which is used for ngModel binding in DOM.

enter image description here

From above example screen, myFirstName is ngModel key has been shown in DOM.

Please advise the possible way to achieve this.

Updated : Is it possible to override the ngModel directive? If so, can we get the key before it get parsed?

like image 544
mymotherland Avatar asked May 10 '26 02:05

mymotherland


1 Answers

You could do that by creating a wrapper object, which would be responsible for holding key & value pair of all dynamic values. That object name could be model inside component.

//inside component
model: any = {};

HTML

<div class='content-wrapper' showModelKey>
  <input [(ngModel)]="model[dynamicKey1]" name="first_name">
  <!-- here myFirstName is ngModel string/key -->
  ....
  <textarea[(ngModel)]="model[dynamicKey2]" name="comment"></textarea>
</div>
like image 181
Pankaj Parkar Avatar answered May 14 '26 10:05

Pankaj Parkar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!