Search code examples
inputoutputangular5ngforngmodel

angular 5, Keeping value on inputs and adding it to JS object


I am making a web tool in angular 5 to help in the creation of new XML.

I am having trouble passing around the values of inputs and keeping them in the same input at the same time.

I Have a form with an event of ngSubmit that uses as a paremeter the reference of an ngForm

<form class="form-group" (ngSubmit)="createSimpleTypeList(f)" #f="ngForm" >
    <div class="container">
        <div class="row">
            <div class="col-sm-12" >
                <button class="btn btn-danger flex ">Construir Json!</button>
            </div>
        </div>
    </div>
    <hr>

    <div class="container" *ngFor="let type of objSimpleType;let i =index">
        <hr>
        <div class="row">
            <div class="col-sm-3">
                <input type="text" [(ngModel)]="type.name" name="nameType"/> 
                <br>
                Inserte el nombre del tipo:     
            </div>
            <div class="col-sm-3">
                <input type="text"    [(ngModel)]="type.type"   name="type"/> 
                <br>
                Inserte el tipo:    
            </div>

            <div class="col-sm-2">
                <input type="number"  [(ngModel)]="type.min"  name="min"/> 
                <br>
                Inserte minimo: 
            </div>
            <div class="col-sm-2">
                <input type="number"  [(ngModel)]="type.max" name="max"/> 
                <br>
                Inserte maximo: 
            </div>
            <div class="col-sm-2">
                <input type="checkbox" name="number" />   Numero?
            </div>
        </div>  
    </div>
    <hr>
</form>

This is the createSimpleTypeList method

console.log(form.value.nameType);
this.objSimpleType.push({
    '-name': form.value.nameType,
    'xsd:restriction': {
        '-base': form.value.type,
        'xsd:minLength': {
            '-value': form.value.min
        },
        'xsd:maxLenght': {
            '-value': form.value.max
        }
    }
});
this.typeList.emit(form.value.nameType);
this.sharedNameSpace.emit(this.namespace);

The problem I am having is that I have not found a way to push new items into objSimpleType, without erasing the value of inputs, and if I manage to not erase the value of the inputs then the values of the form wont push.

this is how it looks.how the inputs work right now

This is what I need

How the inputs should be I am still new to angular, and I would really appreciate the help.


Solution

  • Now that I have looked found the solution, I had two mistakes in the code above.

    First my logic was not well executed, I needed to work with unique IDs,and call them dynamically.

    Second, I was having trouble to call them , and after reading a lot, I found that I can call the parameters of a Json with brackets[].

    "form.value['nameType' + this.i]" --Something like this is what i Needed.