我创建了我的第一个Angular项目。我想验证我的表格。 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;
}
}
为什么我在浏览器控制台中排除了<tr *ngIf="existChildBedInRoom">
此错误:
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)
请解释我收到此错误的原因?它与尚未创建的表格有关吗?
如何解决这个问题?
答案 0 :(得分:1)
首先生成模板,而不是ViewChild
将模板引用绑定到组件变量。首先需要确保绑定模板引用然后使用它。
您可以将运算符(?)与countOfChildBedInput?.invalid