Reputation: 361
I creating my first Angular project. I want to validate my form. html:
<tr
*ngIf="existChildBedInRoom"
class="form-group"
[ngClass]="{'has-error': countOfChildBedInput.invalid && countOfChildBedInput.touched}">
</tr>
<tr *ngIf="existChildBedInRoom">
<td><label class="control-label" for="countOfChildBedInput">Count bed</label></td>
<td>
<input
type="number"
name="countOfChildBedInput"
id="countOfChildBedInput"
placeholder="Enter number"
class="form-control"
required
ngModel
#countOfChildBedInput="ngModel"
>
</td>
</tr>
<tr
*ngIf="countOfChildBedInput.invalid && countOfChildBedInput.touched"
class="text-center form-help-text"
><td colspan="3" style="background: #c40000; color: white">Not emty!</td>
</tr>
ts:
export class RoomInformationCardComponent implements OnInit {
existChildBedInRoom: boolean;
@ViewChild('childBedInRoom') childBedInRoom: ElementRef;
constructor() { }
ngOnInit() {
this.existChildBedInRoom = false;
}
}
Why I getting in line <tr *ngIf="existChildBedInRoom">
this error in browser console:
ERROR TypeError: Cannot read property 'invalid' of undefined
at Object.eval [as updateDirectives] (RoomInformationCardComponent.html:92)
at Object.debugUpdateDirectives [as updateDirectives] (core.es5.js:13067)
at checkAndUpdateView (core.es5.js:12251)
at callViewAction (core.es5.js:12599)
at execComponentViewsAction (core.es5.js:12531)
at checkAndUpdateView (core.es5.js:12257)
at callViewAction (core.es5.js:12599)
at execComponentViewsAction (core.es5.js:12531)
at checkAndUpdateView (core.es5.js:12257)
at callViewAction (core.es5.js:12599)
Please explain why I getting this error? It is related with the form has not yet been created?
How fix this problem?
Upvotes: 0
Views: 625
Reputation: 68665
First your template is generated, than the ViewChild
binds the template reference to the component variable. You need first to be ensured that template reference is bound and then use it.
You can use operator (?) with them countOfChildBedInput?.invalid
Upvotes: 1