如何根据文本框值动态访问javascript对象的属性?

问题描述 投票:1回答:1

我是棱角分明的新手。我坚持生成或更新关于文本框的表格。我有一个架构,其中包含3个字段 - 国家/地区,销售和利润。有两个文本框命名为x和y轴。有一个表应该在更新x和y轴(文本框)时生成。应该是表中的两列,它告诉x和y应该是什么轴。

这是我的home.component.html

<div class="form-group">
        <form [formGroup]="myFormGroup">
            <label>x-axis : </label>
            <input type="text" class="form-control" formControlName = "xaxis" >  <br>
            <label>y-axis : </label>
            <input type="text" class="form-control" formControlName ="yaxis" > <br>
            <button class="apply-btn" (click)='apply(myFormGroup.value)'>Apply</button>
        </form>
    </div>

    <table class="table table-hover">
        <thead>
            <tr>
                <th>{{this.xaxis}}</th>
                <th>{{this.yaxis}}</th>
            </tr>
        </thead>
        <tbody>
            <tr *ngFor = 'let product of products' cdkDrag>
                <td>{{product.xaxis}}</td>    **<----Here is the problem**
                <td>{{product.yaxis}}</td>
            </tr>   
        </tbody>
    </table>

这是我的home.component.ts

export class HomeComponent implements OnInit{

    products:any=[];
    xaxis:any;
    yaxis:any;
    myFormGroup:FormGroup;

    constructor(private service : ServiceService,private fb : FormBuilder) { 
      this.CreateForm();
    }

    //Fetching of data
    refreshData(){
      this.service.getAll().subscribe((res) => {
      this.products=res;
      })  
    } 

    CreateForm(){
      this.myFormGroup=this.fb.group({
        xaxis:['',Validators.required],
        yaxis:['',Validators.required]
      });
    }

  apply(formValue){
    this.xaxis=formValue.xaxis;
    this.yaxis=formValue.yaxis;
  }
  ngOnInit() {
      this.refreshData();
  }
}

值应该在文本框中是模式的属性,即国家,销售和利润。例如,当我们分别输入x轴和y轴的国家和销售额时,表格应该从数据库中获取国家和销售额的值。使用这些值更新表。

javascript html angular mongodb typescript
1个回答
0
投票

您可以使用JavaScript Square Bracket []表示法动态访问产品对象属性。方括号表示法接受表达式,因此您可以在产品对象中传递this.xaxisthis.yaxis。即,product[this.xaxis]

<div class="form-group">
        <form [formGroup]="myFormGroup">
            <label>x-axis : </label>
            <input type="text" class="form-control" formControlName = "xaxis" >  <br>
            <label>y-axis : </label>
            <input type="text" class="form-control" formControlName ="yaxis" > <br>
            <button class="apply-btn" (click)='apply(myFormGroup.value)'>Apply</button>
        </form>
    </div>

    <table class="table table-hover">
        <thead>
            <tr>
                <th>{{this.xaxis}}</th>
                <th>{{this.yaxis}}</th>
            </tr>
        </thead>
        <tbody>
            <tr *ngFor = 'let product of products' cdkDrag>
                <td>{{product[this.xaxis]}}</td>  
                <td>{{product[this.yaxis]}}</td>
            </tr>   
        </tbody>
    </table>
© www.soinside.com 2019 - 2024. All rights reserved.