角度 6 反应式形式控制



我想用 angular 6 做一个小主页。其中一部分是一些测试,如质因数分解和闰年测试。我用反应式表单进行了验证。我的问题是,我无法同时执行这两个功能。

.HTML:

<div class="container">
<form [formGroup]="primForm" (ngSubmit)="onSubmit(primForm.value)" novalidate>
<div class="form-group">
<h3>Primfaktoren</h3>
<label>Name:
<input class="form-control" formControlName="zahl" placeholder="42" #spy>
</label>
<button type="submit" [disabled]="primForm.pristine || primForm.invalid" class="btn btn-success">Zerlegen</button>    
<br>
<div>Die Faktoren sind:</div>
<br>
<div style="display:inline" *ngFor="let faktor of faktoren">{{faktor}}</div>
<br>
</div>
<p>{{spy.className}}</p>
</form>
<form [formGroup]="jahrForm" (ngSubmit)="onSubmit(jahrForm.value)" novalidate>
<div class="form-group">
<h3>Schaltjahrtest</h3>
<label>Jahr:
<input class="form-control" formControlName="jahr" placeholder="2018" #spy1>
</label>
<button type="submit" [disabled]="jahrForm.pristine || jahrForm.invalid" class="btn btn-success">Prüfen</button>
<p>{{jahr}} ist {{prf}} Schaltjahr</p>
</div>
<p>{{spy1.className}}</p>
</form>
</div>

打字稿:

constructor(private fb: FormBuilder) {
this.createForm();
}
createForm() {
this.primForm = this.fb.group({
zahl: ['', Validators.min(3)]
});
this.jahrForm = this.fb.group({
jahr: ['', Validators.min(1)]
});
}
onSubmit(object: Object) {
console.log(object, typeof object);
this.submitted = true;
if (this.primForm.dirty) {
this.help = parseInt(object['zahl'], 10);
this.ergebnis = this.primFaktor(this.help);
} else {
if (this.jahrForm.dirty) {
this.help = parseInt(object['jahr'], 10);
this.prf = this.jahrTest(this.help);
}
}
}
primFaktor(zahl: number): number[] {
this.faktoren = [];
let index = 2;
while (zahl !== 1) {
if (zahl % index === 0) {
this.faktoren.push(index);
zahl /= index;
index = 2;
} else {
index++;
}
}
return this.faktoren;
}
jahrTest(jahr: number): string {
this.antwort = '';
if (jahr % 4 === 0 && (jahr % 100 !== 0 || jahr % 400 === 0)) {
this.antwort = 'ein';
} else {
this.antwort = 'kein';
}
return this.antwort;
}
}

我可以使用 prim 函数,但如果我将使用 year test,则没有任何反应,页面将崩溃。

我在网上什么也没找到。

也许有人有一个想法或解决方法。

谢谢。

我解决了这个问题。将打字稿从:

onSubmit(object: Object) {
console.log(object, typeof object);
this.submitted = true;
if (this.primForm.dirty) {
this.help = parseInt(object['zahl'], 10);
this.ergebnis = this.primFaktor(this.help);
} else {
if (this.jahrForm.dirty) {
this.help = parseInt(object['jahr'], 10);
this.prf = this.jahrTest(this.help);
}
}
}

自:

const key = Object.keys(object);
this.submitted = true;
if (key[0] === 'zahl') {
this.help = parseInt(object['zahl'], 10);
this.ergebnis = this.primFaktor(this.help);
} else {
if (key[0] === 'jahr') {
this.help = parseInt(object['jahr'], 10);
this.prf = this.jahrTest(this.help);
}
}
}

现在我从对象中获取键,函数检查键值。

最新更新