反应形式的value属性不会初始化表单控件名称

时间:2019-02-12 11:04:28

标签: angular typescript angular-reactive-forms

我使用的是反应式表单,我希望通过两种方式进行数据绑定,因此我使用“ value”属性来初始化表单组的默认值。因为表单组位于ngFor循环中,但是当我尝试获取表单时,我只能获取已编辑的值,而无法获取默认值,我似乎“ value”属性不会初始化表单控件,而是仅在DOM中显示。

TS:

 userForm: FormGroup;

 constructor(private fb: FormBuilder){}

 ngOnInit(){
    this.userForm = this.fb.group({
  userName: [''],
  fullName: [''],
  email: [''],
 });
   }

OnUpdateClick() {

 console.log(this.userForm.get('userName').value);
 console.log(this.userForm.get('fullName').value);
 console.log(this.userForm.get('email').value);

 }

HTML:

   <div *ngFor="let agent of agents">

    <form [formGroup]="userForm" >

                    <mat-form-field >
                      <mat-label>Name</mat-label>
                      <input matInput id="Name" name="name" value=" 
                     {{agent.username}}" formControlName="userName">
                    </mat-form-field>

                    <mat-form-field >
                      <mat-label>Name</mat-label>
                     <input matInput id="FName" name="Fname" value=" 
                     {{agent.fullName}}" formControlName="fullName">
                    </mat-form-field>

                      <mat-form-field >
                      <mat-label>Name</mat-label>
                     <input matInput id="email" name="email" value=" 
                     {{agent.email}}" formControlName="email">
                    </mat-form-field>

              <button (click)="OnUpdateClick()"> SAVE </button>

   </div>

当我尝试在“ OnUpdateClick”函数中获取表单字段时,我仅获取那些弄脏的值,未修改的控件也应返回其默认值

2 个答案:

答案 0 :(得分:0)

您需要创建formarray并修补formcontrolname值。

       userForm: FormGroup;

          constructor(private fb: FormBuilder){}
       ngOnInit(){
          this.userForm = this.fb.group({
              userData: this.fb.array([]) 
           });
          this.addUserData();
       }
       get userDataArray() {
           return this.userForm.get('userData') as FormArray;
        }
       addUserData() {
         for (let i = 0; i < this.agents.length; i++) {
            const datas =  this.fb.group({
                 userName: [this.agents[i].userName],
                  fullName: [this.agents[i].fullName],
                  email: [this.agents[i].email],
                 });
      this.userDataArray.push(datas);
        }         
            }
OnUpdateClick() {

 console.log(this.userForm.value);

 }

按如下所示更改您的html; ngfor用于激活表单数组并添加formarray    名称。不需要绑定值。

    <form [formGroup]="userForm" >
 <div formArrayName="userData">
      <div *ngFor=" let agent of userDataArray.controls;let i = index" [formGroupName]="i">
                        <mat-form-field >
                          <mat-label>Name</mat-label>
                          <input matInput id="Name" name="name"  formControlName="userName">
                        </mat-form-field>

                        <mat-form-field >
                          <mat-label>Name</mat-label>
                         <input matInput id="FName" name="Fname"  formControlName="fullName">
                        </mat-form-field>

                          <mat-form-field >
                          <mat-label>Name</mat-label>
                         <input matInput id="email" name="email"  formControlName="email">
                        </mat-form-field>



                       </div>
            </div>
          <button (click)="OnUpdateClick()"> SAVE </button>
             </form>

答案 1 :(得分:0)

Raza,首先要说的是,使用ReactiveForm,实际上我们不是在绑定数据,而是创建一个表单,以便在form.value中拥有数据。您可以在.html中看到写内容-仅供检查-

{{userForm?.value|json}}

我喜欢创建类似的功能

constructor(private fb: FormBuilder){}

createForm(data:any):FormGroup
{
   return this.fb.group({
      userName: [data?dat.userName:null],
      fullName: [data?dat.fullName:null],
      email: [data?dat.email:null],
   });
}

如果您有唯一的代理商,什么时候可以代理商

ngOnInit(){
    this.userForm = this.createForm(agent);
}

如果您的座席来自服务呼叫

ngOnInit(){
    this.mayService.getAgent().subscribe(data=>
    {
        this.userForm = this.createForm(data);
    })
}

好吧,您有一系列的Agent,但我不知道您想在userForm .value中得到什么。如果要获取对象数组,请考虑Dhara的回复和我的评论

myArrayForm:ArrayForm; //declare an array Form
ngOnInit(){
    this.myArrayForm= this.fb.array(agents.map(a=>this.createForm(a));
    //Its a abreviate way to say
    //this.myArrayForm=[];
    //for (let i = 0; i < this.agents.length; i++) {
    //     this.userDataArray.push(agents[i]);
    //}       
}

.html

<form [formGroup]="myArrayForm" (submit)="save(myArrayForm)" >
      <div *ngFor=" let agent of myArrayForm.controls;let i = index"
           [formGroupName]="i">
         <mat-form-field >
             <mat-label>User Name</mat-label>
             <input matInput id="Name" name="name"  formControlName="userName">
         </mat-form-field>
         <mat-form-field >
              <mat-label>Full Name</mat-label>
              <input matInput id="FName" name="Fname"  formControlName="fullName">
         </mat-form-field>
         <mat-form-field >
              <mat-label>E-mail</mat-label>
              <input matInput id="email" name="email" formControlName="email">
         </mat-form-field>
      </div>
    </div>
    <button> SAVE </button>
</form>

save(myForm)
{
   console.log(myForm.value)
}

但是您可能想要一个FormGroup数组

myArray:FormGroup[] //declare an array of FormGroup
ngOnInit(){
    this.myArray= agents.map(a=>this.createForm(a));
    //Its a abreviate way to say
    //this.myArray=[];
    //for (let i = 0; i < this.agents.length; i++) {
    //     this.myArray.push(this.createForm(agents[i]));
    //}       
}

.html

<form *ngFor="let form of myArray" [formGroup]="form">
     <mat-form-field >
         <mat-label>User Name</mat-label>
         <input matInput id="Name" name="name"  formControlName="userName">
     </mat-form-field>
     <mat-form-field >
          <mat-label>Full Name</mat-label>
          <input matInput id="FName" name="Fname"  formControlName="fullName">
     </mat-form-field>
     <mat-form-field >
          <mat-label>E-mail</mat-label>
          <input matInput id="email" name="email" formControlName="email">
     </mat-form-field>
</form>
<button (click)"save()"> SAVE </button>

save()
{
    myArray.forEach(form=>{
        console.log(form.value)
    }
}