vishnu
vishnu

Reputation: 197

Is it possible to change the name of a variable dynamically in Angular?

I have a component and within that there is another Angular component.

<div *ngFor="let locs of nhsnLocationCodeType;let i=index">
    <div class="floatLeft gray-Box" *ngIf="locs.code !=''">
        <div class="floatLeft paddingL" style="width: 16%;">
            <label class="location-type-label">
                {{locs.code}} (<span *ngFor="let l of locs.location; last as islast">
                {{locs.code}}{{l}}<span *ngIf="!islast">,</span>
            </span>)
                <p class="selectDate">
                    {{ selectedDateOP | date:"MMM yyyy" | uppercase}}
                </p>
            </label>
        </div>
        <div class="floatLeft paddingL" style="width: 26%;">
            <div class="gray-Box-row">
                <div class="floatLeft facwide-days-labels">
                    <span *ngIf="locs.locType == 'display'">24 hour Oberservation</span>
                    <span *ngIf="locs.locType == 'Emergency'">Emergency</span>
                    <span *ngIf="locs.locType == 'Pediatric Emergency'">Pediatric Emergency</span>
                    <br>Outpatient Encounters
                </div>
                <div class="floatLeft facwide-days-textbox-div">
                    <input id="opEncounters{{i}}"
                           class="facwide-days-textbox record-input"
                           #opEncounters
                           maxlength="5"

                    >
                </div>
            </div>
        </div>
        <!-- <app-noevent></app-noevent>-->
        <app-noevent id="noEvent{{i}}" [specimen]="specimenTypeOrganismStatus" (isEdited)="setEditSat($event)" (notifyAccess)="setAccessStatus($event)"></app-noevent>

    </div>
    <div class="floatLeft paddingL" style="width: 6%;">&nbsp;</div>
</div>

the ts file is

specimenTypeOrganismStatus = {
        mrsa_AllSpecimens: false,
        mrsa_BloodOnly: false,
    };

ts file of app-noevent is

 specimenTypeOrganism = {
        mrsa_AllSpecimens: false,
        mrsa_BloodOnly: false,
        };
    @Input() specimen;

I have a variable in the parent component say for example specimenOrganismType and that is used in the app-noevent. app-noevent has some check boxes so if I click a check box in any one div element, the same check box in all the div elements are getting selected. Please tell me how to solve this issue.

Upvotes: 0

Views: 924

Answers (1)

Garrett Witzenburg
Garrett Witzenburg

Reputation: 51

This is probably more complex than what you want, but this should be the most preferred approach. From a high level, you create a form, and nest a form array within that form. The form controls are assigned to each "i-th" index of your array. So your controls are dynamically controlled by the user and their corresponding values. See the stackblitz.

The dynamic variable names are actually controls in this instance. Where each instance of a form control is assigned to the value of i.

//Child TS file
//This is how you emit your form back to your parent
@Output() sendToParent: EventEmitter<any> = new EventEmitter<any>();

//initialization of the form
form: FormGroup = this.fb.group({
     formArray = this.fb.array([])
})

items = [
{
    mrsa_AllSpecimens: false,
    mrsa_BloodOnly: true,
}
];

ngOninit() {
this.pushValuesOntoArray() //This is arbitrarily pushing true/false values. This can be anything.
}

pushValuesOntoArray() {
this.items.forEach(value => {
  console.log(value?.mrsa_AllSpecimens)
  this.formArray.push(this.fb.control(value?.mrsa_AllSpecimens))
  this.formArray.push(this.fb.control(value?.mrsa_BloodOnly))
})


sendFormToParent() {
    this.sendToParent.emit(this.form)
  }

//child HTML
<button (click)="sendFormToParent()">Send the form</button>

//parent HTML
<child (sendToParent)="handleChildForm($event)"></child>

//parent TS
handleChildForm(form: FormGroup) {
let formArray = form.get('formArray') as FormArray
formArray.controls.forEach((controlItem, i) => {
  console.log('variable name ' + i)
  console.log('value ' + controlItem.value)
})

}

https://stackblitz.com/edit/angular-ivy-kgmns3?file=src%2Fapp%2Fchild%2Fchild.component.ts

After the form has been sent back to the parent, you can see in the console that each respective control in the formGroup -> formArray is equal to the ith value of the initial array. So your variable names as such would be in your parent: 0 and 1 respectively.

Are the keys: mrsa_all / mrsa_blood always present in every GET call or sometimes not present? Or is there sometimes more keys than that? If so you will have to check to see if that key exists

Upvotes: 1

Related Questions