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

时间:2019-02-25 05:46:06

标签: javascript html angular mongodb typescript

我是angular的新手。我一直在针对文本框生成或更新表。 我有一个包含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轴上输入国家/地区和销售额时,表格应从以下位置获取国家/地区和销售额的值:数据库,并使用这些值更新表。

1 个答案:

答案 0 :(得分:0)

您可以使用 JavaScript方括号 []表示法来动态访问产品对象属性。方括号表示法接受表达式,因此您可以在产品对象中传递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>
相关问题