Cześć,
Mam pewien problem z walidacją w Angularze 8. Podążam za samouczkiem z oficjalnej strony i ciągle dostaję "Cannot read property 'invalid' of undefined".
Kod HTML:
<div class="container">
<div class="row">
<form [formGroup]="mathFactForm" (ngSubmit)="onSubmit(mathFactForm)">
<label>
Number:
<input id="number" type="text" formControlName="number" required>
</label>
<div *ngIf="number.invalid && (number.dirty || number.touched)" class="alert alert-danger">
<div *ngIf="number.errors.required">
Name is required.
</div>
</div>
<label>
Fragment:
<input type="text" formControlName="fragment">
</label>
<button type="submit" [disabled]="!mathFactForm.valid">Submit</button>
</form>
</div>
</div>
Kod TS:
import { MathFactModel } from './../../models/MathFactModel';
import { FormBuilder, FormsModule, Validators, FormGroup, FormControl } from '@angular/forms';
import { NumbersApiService } from './../../services/numbers-api.service';
import { Component, OnInit, NgModule } from '@angular/core';
@Component({
selector: 'app-math-facts',
templateUrl: './math-facts.component.html',
styleUrls: ['./math-facts.component.less']
})
export class MathFactsComponent implements OnInit {
mathFactForm: FormGroup;
numberControl: FormControl;
fragmentControl: FormControl;
mathFact;
mathFactModel: MathFactModel;
constructor(private numbersApiService: NumbersApiService,
private formBuilder: FormBuilder) {
this.mathFactForm = this.formBuilder.group({
number: ['', Validators.required],
fragment: ''
});
}
ngOnInit() {
}
onSubmit(mathFactModel) {
console.log(mathFactModel);
console.log(this.mathFactForm.value);
}
}
W momencie jak zmienię
<div *ngIf="number.invalid && (number.dirty || number.touched)" class="alert alert-danger">
na
<div *ngIf="mathFactForm.invalid && (mathFactForm.dirty || mathFactForm.touched)" class="alert alert-danger">
Błąd przestaję się wyświetlać, ale to jest walidacja całego formularza, a nie potrafię się dobrać do walidacji poszczególnych kontrolek. Próbowałem się dobrać do konkretnych właściwości w ten sposób
mathFactForm['controls']['number']
Niestety bez większego rezultatu. Ktoś wie gdzie co robię źle?
Pozdrawiam