//... imports: [ ReactiveFormsModule ];
<form [formGroup]="loginForm"> <div class="form-group"> <label>E-mail</label> <input type="email" class="form-control" formControlName="email"> </div> <div class="form-group"> <label>Jelszó</label> <input type="password" class="form-control" formControlName="password"> </div> <button type="submit" class="btn btn-primary">Belép</button> </form>
import { FormControl, FormGroup, Validators } from '@angular/forms'; //... export class AppComponent { loginForm = new FormGroup({ email: new FormControl('', Validators.required), password: new FormControl('') }) }
Ha invalid, látszik a böngésző fejlesztői felületén, az Elements fülön.
<input class="form-control" ng-invalid> ^^^^^^^^^^
Ha érvényes:
ng-valid
Az attribútum alapján lehet egy kis piros széle, CSS-sel:
input.ng-invalid { border-left: 5px solid red; }
input.ng-valid { border-left: 5px solid green; }
export class LoginComponent implements OnInit { loginForm !: FormGroup; constructor() { } ngOnInit(): void { this.loginForm = new FormGroup({ email: new FormControl('', Validators.required), password: new FormControl(''), }) } }
Kötelezőnek jelölés és email:
email: new FormControl('', [Validators.required,Validators.email])
Minta használata:
name: new FormControl('', Validators.pattern('[a-z]'))
export class LoginComponent implements OnInit { loginForm !: FormGroup; constructor(private formBuilder: FormBuilder) { } ngOnInit(): void { this.loginForm = this.formBuilder.group({ email: ['', [Validators.required, Validators.email]], password: ['', Validators.required] }) } }
<small *ngIf="loginForm.controls.email.invalid">
<small *ngIf="loginForm.controls.email.invalid && loginForm.controls.email.touched">
<small *ngIf="loginForm.controls['email'].invalid">
<small *ngIf="loginForm.controls['email'].invalid && loginForm.controls['email'].touched">
//... export class LoginComponent implements OnInit { loginForm !: FormGroup; constructor() { } ngOnInit(): void { this.loginForm = new FormGroup({ email: new FormControl('', Validators.required), password: new FormControl('') }) } get email(){return this.loginForm.controls['email']} }
<!-- ... --> <small *ngIf="email.invalid">E-mail kötelező</small> <!-- ... -->
<!-- ... --> <small *ngIf="email.invalid && email.touched">E-mail kötelező</small> <!-- ... -->