一次性获取响应式表单值

Get Reactive Form Values In One Go

我创建了一个 Angular 项目,用户可以在其中提供输入并验证表单,如下所示:

<form [formGroup]="angForm" novalidate>
    <div class="form-group">
        <label>Name:</label>
        <input class="form-control" [(ngModel)]="name" formControlName="name" type="text" />
    </div>
    <div *ngIf="angForm.controls['name'].invalid && (angForm.controls['name'].dirty || angForm.controls['name'].touched)" class="alert alert-danger">
        <div *ngIf="angForm.controls['name'].errors.required">
          Name is required.
        </div>
    </div>
     <div class="form-group">
        <label>Address:</label>
        <input class="form-control" [(ngModel)]="address" formControlName="address" type="text" />
    </div>
    <div *ngIf="angForm.controls['address'].invalid && (angForm.controls['address'].dirty || angForm.controls['address'].touched)" class="alert alert-danger">
        <div *ngIf="angForm.controls['address'].errors.required">
          email is required.
        </div>
    </div>
    <button type="submit" (click)="buttonClicked()" class="btn btn-success">
        Save
    </button>
</form>

因为这是一种反应形式,我尝试按如下方式从输入中检索值,并在文本字段中分配了 ngModel 属性:

<input class="form-control" [(ngModel)]="name" formControlName="name" type="text" />

TypeScript中,我正在做如下事情:

export class SampleComponent implements OnInit {

    constructor(private fb: FormBuilder) {
       this.validateForm();
    }

    ngOnInit() {

    } 

    angForm: FormGroup;
    name: string;
    address: string;

    //Retrieve value from input field on button click
    buttonClicked() {
       alert("Button works with the value: " + this.name);
    }
}

效果很好,我得到了预期的结果。但是我有一个有很多属性的模型。举个例子:

export class SampleClass {
   name: string;
   address: string;
   ................
   With other lot of fields
}

所以我的问题是,如果我在前端定义的 ngModel 中具有相同的模型属性,我可以做这样的事情吗?定义如下:

this.SampleClass = this.angForm.value; //So all properties can be retrieved in one go

现在,我正在做的是将所有属性一一绑定如下:

obj: SampleClass ;

this.obj = new SampleClass();
this.obj.name= this.name;
this.obj.address= this.address;

 

如果您使用反应式表单,这意味着您不应使用 ngmodel,您可以使用 getRawValue() 方法检索表单的值。

勾选这个angular guide on how to create a reactive form