javascript - How to normally bind forms in angular -
i have template form, wrote guides , don't work though. have several of models:
export class user { constructor(public userid?: userid, public firstname?: string, public lastname?: string, public address?: address) { } } export class address { constructor( public street?: string, public city?: string, public zipcode?: string) { } }
i have component:
component({ templateurl: 'user.html' }) export class mycomponent implements oninit, ondestroy{ user: user; userform: ngform; ngoninit(): void { }
and page itself:
<form novalidate #userform="ngform"> <div class="form-group"> <input required minlength="4" type="text" id="firstname" [(ngmodel)]="user.firstname" name="firstname"> <small *ngif="!firstname.valid">not valid!</small> </div> <div class="form-group"> <input required ng-minlength="4" type="text" id="lastname" [(ngmodel)]="user.lastname" name="lastname"> </div> <div ngmodelgroup="user.address"> <div class="form-group"> <input required ng-minlength="4" type="text" id="address-house" [(ngmodel)]="user.address.address1" name="address.address1"> </div> <div class="form-group"> <div class="form-group"> <input required ng-minlength="4" type="text" id="zipcode" [(ngmodel)]="user.address.zipcode" name="address.zipcode"> </div> <div> <input required ng-minlength="4" type="text" lass="form-control input-lg" id="city" [(ngmodel)]="user.address.city" name="address.city"> </div> </div> </div> <button type="button" (click)="checkandproceed()">continue</button> </div> </form>
the thing want add validation - that's all. none of guides helped. can in-html validation or ts validation? nice call validation when clicking 'continue' button , making valid if so.
in case of validation additionally console error: cannot read property 'valid' of undefined
there lots of attributes on input elements. have name, id, , template reference variable. code missing template reference variable. template reference variable holds onto reference element , has valid, dirty, , other flags associated it.
for example, change code include template reference variable this:
<div class="form-group"> <input required minlength="4" type="text" id="firstname" [(ngmodel)]="user.firstname" name="firstname" #firstnamevar="ngmodel"> <small *ngif="!firstnamevar.valid">not valid!</small> </div>
notice #firstnamevar
. template reference variable. can named same thing id , name attributes. named different readily distinguished between other 2 attributes.
notice *ngif changed use firstnamevar.valid
for more information on template reference variables, see this: https://angular.io/guide/template-syntax#ref-vars
Comments
Post a Comment