我想通过传递的ID更新数据库中的一行。如何使用FormBuilder传递对象的id更新
我有一个表单组件,你可以看到我用的反应formBuilder:
@Component({
selector: 'program-form',
templateUrl: './program.form.component.html',
styleUrls: ['./program.form.component.css']
})
export class ProgramFormComponent implements OnInit {
form: FormGroup;
title: string;
program: ProgramModel = new ProgramModel();
constructor(
formBuilder: FormBuilder,
private router: Router,
private route: ActivatedRoute,
private dataService: DataService
) {
this.form = formBuilder.group({
name: ['', [
Validators.required,
Validators.minLength(3)
]],
// email: ['', [
// Validators.required,
// BasicValidators.email
// ]],
// phone: [],
// address: formBuilder.group({
// street: ['', Validators.minLength(3)],
// suite: [],
// city: ['', Validators.maxLength(30)],
// zipcode: ['', Validators.pattern('^([0-9]){5}([-])([0-9]){4}$')]
// })
});
}
ngOnInit() {
var id = this.route.params.subscribe(params => {
var id = params['id'];
this.title = id ? 'Edit' : 'New';
if (!id)
return;
this.getProgram(id);
});
}
private getProgram(id: number) {
this.dataService.setEndpoint('/api/program/getsingle');
this.dataService
.GetSingle(id)
.subscribe(data => {
this.program = data
}, (error) => {
console.log(error);
});
}
create() {
var result,
userValue = this.form.value;
console.log(userValue.Id + ", userValueId");
if (userValue.id){
this.dataService.setEndpoint('/api/program/update');
result = this.dataService.Update(userValue.Id, userValue);
}
else
{
this.dataService.setEndpoint('/api/program/create');
this.dataService.Create(userValue).subscribe(data => {
(data => this.router.navigate(['users']));
}, (error) => {
console.log(error);
});;
}
//result.subscribe(data => this.router.navigate(['users']));
}
}
HTML:
<div class="row">
<form materialize class="col s12" [formGroup]="form" (ngSubmit)="create()">
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">account_circle</i>
<label for="name"
[class.active]="program.name"
data-error="Name is required and needs to contain at least 3 chars">
Name
</label>
<input id="name" type="text" class="validate"
[(ngModel)]="program.name" formControlName="name"
[class.invalid]="form.controls['name'].touched && !form.controls['name'].valid">
</div>
</div>
<button class="btn waves-effect waves-light" type="submit">
Submit<i class="material-icons right">send</i>
</button>
</form>
</div>
如何从this.form.value为您检索ID可以看到我试图获得id,但console.log说它是未定义的。我是否需要在表单构建器或html内部初始化它?
哪里有id?我看不到任何你想传递它的地方?'我瞎了吗:D – Alex
你甚至没有在你的html中使用formbuilder? – Alex
你能解释一下吗?我不确定你的意思。 –