Angular 6 Reactive表单映射对象



我想从Reactive表单映射我的英雄对象的值,但它不起作用。

这是我的hero-add.component.ts:

import { Component, OnInit, Input } from '@angular/core';
import { Hero } from '../Hero';
import { HeroService } from '../hero.service';
import { Router } from '@angular/router';
import { FormBuilder, FormGroup, Validators, ReactiveFormsModule } from
'@angular/forms';
@Component({
selector: 'app-hero-add',
templateUrl: './hero-add.component.html',
styleUrls: ['./hero-add.component.css']
})
export class HeroAddComponent implements OnInit {
hero: Hero = new Hero();
myForm = new FormGroup({}) // Instantiating our form
get f() { return this.myForm.controls; }
constructor(private heroService: HeroService, private router: Router,
private formBuilder: FormBuilder) {
this.myForm = formBuilder.group({
publishedYear: [this.hero.Name, [Validators.required,
Validators.min(1990), Validators.max(2018)]],//I expect this will map value of name from form to my this.hero.Name
name: [this.hero.PublishedYear, [Validators.required,
Validators.minLength(2)]] //I expect this will map value of publishedDate from form to my this.hero.Published
});
}
ngOnInit() {
}
addHero() {
var hr = this.hero;//hr= Hero {} because this.hero = Hero{} 
}
}

这是我的hero-add.component.html:

<div>
<form [formGroup]="myForm">
<div class="name">
<label for="name">Name: </label>
<input type="text" id="Name" formControlName="name">
<p class="alert alert-danger invalid" *ngIf="f.name.errors">Invalid Name</p>
</div>
<div class="publishedYear">
<label for="publishedYear">Publish Year: </label>
<input type="number" id="PublishedYear" formControlName="publishedYear">
<p class="alert alert-danger invalid" *ngIf="f.publishedYear.errors">Invalid Published Year</p>
</div>
</form>
<div class="complete">
<label>Complete</label>
<input type="radio" id="Complete" name="Complete" [(ngModel)]="hero.Complete" value="true">Yes
<input type="radio" id="Complete" name="Complete" [(ngModel)]="hero.Complete" value="false">No
</div>
<button (click)='addHero()'>Add new</button>
</div>

我输入字段名称和发布年份,然后单击按钮";添加英雄"以转到函数CCD_ 1。我在这个函数中设置了一个断点,this.Hero的值为空。我不明白为什么值不能从表单映射到我的对象。

我该如何解决这个问题?

您的函数addHero必须像一样

addHero()
{
if (this.myform.valid)
{
var hr=this.myForm.value;
}
}

或者更好的是,您可以更改.html并将表单作为变量传递

<button (click)='addHero(myForm)'>Add new</button>
//And addHero receive as argument
addHero(form)
{
if (form.valid)
{
var hr=form.value;
}
}

一个是"英雄数据"(你的可变英雄(,另一个是你的可变"myForm"的"英雄形态">

相关内容

  • 没有找到相关文章

最新更新