我有模型驱动的表单,我正在尝试console.log this.userForm.email,但它给了我以下错误:'FormGroup'类型中不存在属性'email'。有人可以帮忙吗?
app.component.html
<div class="container">
<h2>User Data</h2>
<form [formGroup]="userForm" (ngSubmit)="onSubmit()">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" formControlName="name">
</div>
<div class="form-group">
<label>Email</label>
<input type="text" #refName class="form-control" formControlName="email">
<b>{{refName.className}}</b>
</div>
<div formGroupName="address">
<div class="form-group">
<label>Street</label>
<input type="text" class="form-control" formControlName="street">
</div>
<div class="form-group">
<label>City</label>
<input type="text" class="form-control" formControlName="city">
</div>
<div class="form-group">
<label>PostalCode</label>
<input type="text" class="form-control" formControlName="postalcode">
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { ReactiveFormsModule } from '@angular/forms'; // see peab olema
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
ReactiveFormsModule,
HttpModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts
import { Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms'
@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.css']
})
export class AppComponent {
userForm = new FormGroup({
name: new FormControl('Brandon'),
email: new FormControl(),
address: new FormGroup({
street: new FormControl(),
city: new FormControl(),
postalcode: new FormControl()
})
});
onSubmit(){
console.log(this.userForm.email);
}
}
答案 0 :(得分:1)
改为使用this.userForm.controls.email.value
。