首页 > 解决方案 > 是否可以在 Angular 中动态更改变量的名称?

问题描述

我有一个组件,其中还有另一个 Angular 组件。

<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>

ts文件是

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

app-noevent 的 ts 文件是

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

我在父组件中有一个变量,例如 sampleOrganismType,它在 app-noevent 中使用。app-noevent 有一些复选框,所以如果我单击任何一个 div 元素中的复选框,所有 div 元素中的相同复选框都会被选中。请告诉我如何解决这个问题。

标签: angulartypescript

解决方案


这可能比您想要的更复杂,但这应该是最首选的方法。从高层次上讲,您创建了一个表单,并在该表单中嵌套了一个表单数组。表单控件分配给数组的每个“第 i 个”索引。因此,您的控件由用户及其相应的值动态控制。请参阅堆栈闪电战。

在这种情况下,动态变量名称实际上是控件。表单控件的每个实例都分配给 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

将表单发送回父级后,您可以在控制台中看到 formGroup -> formArray 中的每个控件都等于初始数组的第 i 个值。因此,您的变量名称将在您的父级中:分别为 0 和 1。

密钥:mrsa_all / mrsa_blood 是否始终存在于每个 GET 调用中,或者有时不存在?或者有时有比这更多的键?如果是这样,您将不得不检查该密钥是否存在


推荐阅读