[(ngModel)] value from json

319 views
Skip to first unread message

celg...@neox.cl

unread,
Sep 28, 2018, 7:41:59 AM9/28/18
to Angular and AngularJS discussion
Hello to every one, Im generating inputs fields names from a json file, I want dynamics fields, but I cant assign a value to [(ngModel)]

I have this error 

Uncaught Error: Cannot assign to a reference or variable!
    at _AstToIrVisitor
.push../node_modules/@angular/compiler/fesm5/compiler.js._AstToIrVisitor.visitPropertyWrite (compiler.js:15702)
    at
PropertyWrite.push../node_modules/@angular/compiler/fesm5/compiler.js.PropertyWrite.visit (compiler.js:2833)


This is my code

        <div *ngFor="let input of inputs.metadatas">
         <mat-form-field class="mat_form_width">
           <input matInput placeholder="{{input | titlecase}}" [(ngModel)]="input" name="input">
         </mat-form-field>
       </div>

{
  "metadatas": [
    "rut",
    "name"
  ]
}

If I delete ngModel, placeholder and name has the right values for every input, If I test using hard coded value to ngModel, works



Riccardo Sadocchi

unread,
Sep 28, 2018, 12:59:40 PM9/28/18
to Angular and AngularJS discussion
Hi,
try the changes below
 
        <div *ngFor="let input of inputs.metadatas">
         <mat-form-field class="mat_form_width">
           <input matInput placeholder="{{input | titlecase}}" [(ngModel)]="inputs.metadatas.indexOf(input)"
name="'name_' + inputs.metadatas.indexOf(input).toString()">
         </mat-form-field>
       </div>

I'm not sure it works, and is not the right way, you should use a FormGroup (no ngModel) and in the html bind with formControlName attribute.
    You can create a Class like {controlName: string, controlValue: string, controlPlaceHolder: string} and use an array oh this to build dynamically the html tags

Sander Elias

unread,
Sep 28, 2018, 11:12:31 PM9/28/18
to Angular and AngularJS discussion

Hi Celgueta,

I assume the metadata lists the property names you want to use. where are those properties stored?

<input matInput placeholder="{{input | titlecase}}" [(ngModel)]="destination[input]" name="input">

in there destination is the target object where your data is going to end up.
Is this what you are looking for?

Regards
Sander

Reply all
Reply to author
Forward
0 new messages