如何在标签中使用表格控件名称-角反应形式

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

我使用的是角反应形式,在我的表单中,一个包含标签的字段用于填充值,其余所有字段均包含表单控件名称。我正在尝试通过订阅设置服务中的数据。因此,在这里,我能够通过控件名称(除label之外)填充所有表单数据。由于标签不包含表单控件名称,因此我无法为其设置值。

这是我的表格:

<div [formGroup]="myForm">
    
            
                <label>
                Roll number
                </label>
         
          
              <label>
                {{rollnum}}
              </label>
            
</div>

通常,我现在正在设置其他类似的字段myForm.control.formcontrolname.setValue('value');

如果是相同的组件,则可以为rollnum分配值,以便填充该值,但是如何从其他服务中为rollnum设置值,并且可以使用任何方法为该标签使用formcontrolname。

angular angular-reactive-forms
1个回答
0
投票

查看您的评论,我了解到,只有从服务加载数据后,才需要在{{rollnum}}上显示内容。

请在下面尝试此代码在您的ts文件中,声明一个变量调用dataLoaded。此变量将是一个布尔值,可以包含true和false值。最初,我们将其设置为false。

dataLoaded : boolean = false;

[下一步,我们将调用该服务以加载数据。

serviceToLoadData(){
   this.serviceCall.getdata().subscribe((data)=>{
    // here you would do the processing of the data and the data will be loaded to 
    //rollnum.
    //Once the data is loaded set the value of dataLoaded to true.
    this.dataLoaded = true;
   });
}

在您的HTML文件中

<div [formGroup]="myForm">


                <label class="bx--label" style ="margin-left: 4rem">
                Roll number
                </label>


              <label *ngIf="dataLoaded" class="bx--label" style ="margin-left: 1rem">
                {{rollnum}}
              </label>

</div>

在这种情况下,只有在dataLoaded为true时,才会显示标签。

您可以将相同的原理应用于div。在div上,您可以应用ngIf。

希望这可以解决问题。

© www.soinside.com 2019 - 2024. All rights reserved.