Validation using if statement using input binding in Angular - html

I am creating a reusable component for Input field. I created a Boolean tag named "IsValid" inside my typescript file to show validation message.
My typescript file
export class InputControlsComponent implements OnInit {
#Input() IsValid;
#Input() className;
#Input() controlName;
#Input() inputType;
constructor() { }
ngOnInit() {
}
}
Html File
<div>
<input type="{{inputType}}" class="{{className}}" >
<span class="error-message" *ngIf="!IsValid">This Field is required</span>
</div>
How it is being used
<div>
<label>Name</label>
<app-input-controls inputType="text" controlName="Address" className="form-control" IsValid = "false">
</app-input-controls>
</div>
I am able to change the value of the Boolean tag of typescript file but the error message is not changing on change of the Boolean tag.

You can use ngModel like [(IsValid)],
If you use ngModel,your model is binding two way.
For example set your html
<app-input-validation [inputType]="'text'" [controlName]="Address" [className]="form-control" [(IsValid)]="isValidDate">
</app-input-validation>
You can set isValid property on parent component whenever you want.
Only write this.isValidText=true;
Please examine example

change !IsValid to IsValid. it will work
<div>
<input type="{{inputType}}" class="{{className}}" >
<span class="error-message" *ngIf="IsValid">This Field is required</span>
</div>

Related

Angular input's ngModel and Value don't work together

I have a problem with the form in angular. My goal is to make a form that is filled with default values ​​that can be changed. After validating the form, it sends the data to the MySQL database.
This is component.html code:
<form #adopt="ngForm" (ngSubmit)="success()">
<label for="email">Email:</label>
<input type="email" name="email" [(ngModel)]="adoptions.email" #email="ngModel">
<label for="animal">Twój wybór to:</label>
<input type="text" name="animal" [(ngModel)]="adoptions.animal" #email="ngModel">
<button [disabled]="adopt.form.invalid" type="submit">Adoptuj</button>
<button (click)="getAnimal('')" class="disable">Odznacz swój wybór</button>
</form>
This is typeScript code:
export class AdoptpageComponent implements OnInit {
adoptions = new Adoptions();
sessionValue
animal
value
msg='';
constructor(private userService: UserService, private shared: SharedService, private _service
: AdoptService, private _router : Router) {
}
ngOnInit(): void {
this.getUsers();
this.sessionValue = sessionStorage.getItem('email');
}
getAnimal(arg) {
this.animal = arg;
}
success() {
this._service.create(this.adoptions).subscribe(
data => {
console.log("dziala");
this._router.navigate(['/adopt'])
},
error => {
console.log("nie dziala");
this.msg = error.error;
}
)
}
}
The code I posted above works, but only when I enter the value into the form from the keyboard. I want the value from sessionValue to be retrieved automatically in the first form and animal in the second. I managed to achieve it when instead of ngModel I entered:
<input type="email" name="email" [value]="sessionValue" #email="ngModel">
But then the form does not work (it does not send data to the database). Unfortunately, when both are used, [value] = "sessionValue" does not work
<input type="email" name="email" [value]="sessionValue" [(ngModel)]="adoptions.email" #email="ngModel">
do you have an idea what to do to be able to submit the form with the default value?
first: you are binding adoptions.email and adoptions.animal to ngModel, but they are empty(or even worse - null or undefined) when ngOnInit is fired, that is why your inputs are empty. They get value once you introduce text in inputs, that is why you are able to successfully execute this._service.create
second: you are causing a value binding conflict. The source of ngModel is different from the source of value. Once ngOnInit is fired value tries to load the value of sessionValue in input and ngModel tries to load nothing, as its source is empty
There is no need to use value if you have ngModel. You just have to set up start point value for its source variable. like below example
ngOnInit(): void {
adoptions.email = somehowGetEmail()
adoptions.animal= somehowGetAnimal()
}
And that's all you have to do, if you insist on using ngModels.
But in general this looks like a lot of unnccessary bindings. Since these are a form inputs you should be using form's preimplemented features for value bindings. Check docs for angular FormBuilder, formControl

Error: formGroup expects a FormGroup instance. Please pass one in. Reactive forms Angular

I am using reactive forms in Angular version 10. But getting the following error.
ERROR Error: formGroup expects a FormGroup instance. Please pass one in.
Example:
<div [formGroup]="myGroup">
<input formControlName="firstName">
</div>
In your class:
this.myGroup = new FormGroup({
firstName: new FormControl()
});
at Function.missingFormException (forms.js:1700:1)
at FormGroupDirective._checkFormPresent (forms.js:5632:1)
at FormGroupDirective.ngOnChanges (forms.js:5454:1)
at FormGroupDirective.rememberChangeHistoryAndInvokeOnChangesHook (core.js:2373:1)
at callHook (core.js:3285:1)
at callHooks (core.js:3251:1)
at executeInitAndCheckHooks (core.js:3203:1)
at selectIndexInternal (core.js:6324:1)
at ɵɵadvance (core.js:6306:1)
at PatientInformationComponent_Template (template.html:39:34)
My sample HTML code is as follows.
<div [formGroup]="MyForm">
<input formControlName="firstName">
<input formControlName="lastName">
</div>
My TS code:
export class MyComponent implements OnInit{
MyForm: FormGroup;
constructor( private formbuilder: FormBuilder) {}
ngOnInit() {
this.MyForm= this.formbuilder.group({
firstName: new FormControl("", Validators.maxLength(100)),
lastName: new FormControl("",Validators.maxLength(100)),
});
}
}
Although the form works properly, but the error always shows in the console. I think it might be because of some other lifecycle hook. Could you give me some solution for this.
Since you haven't initialized your form called myForm in .ts code, you should try adding *ngIf and change div HTML tag to form element.
<form *ngIf="form"
[formGroup]="MyForm">
<input formControlName="firstName">
<input formControlName="lastName">
</form>
i had the same issue., for me it was
i declared the form in component.ts
form: FormGroup = this._fb.group({})
and in component.html i used
<form [formGroup]="studentForm" (ngSubmit)="onSubmit()">
i used different names in each place
i had to use same form name in both component.html and component.ts

check if (child) form is dirty in nested reactive forms

I have a form with different sections (nested formgroups)
How can you check if something changes in a specific section.
HTML:
<div [formGroup]="formGroup">
<div formGroupName="one">
<input type="text" formControlName="email">
<input type="text" formControlName="name">
<div>
</div>
TS:
export class someClass implements OnInit {
formGroup = this.formBuilder.group({
one: this.formBuilder.group({
email: [null, [Validators.required, Validators.pattern('^[a-z0-9._%+-]+#[a-z0-9.-]+\\.[a-z]{2,4}$')]],
name[null],
})
});
get emailControl(): AbstractControl { return this.formGroup.get('one.email'); }
get nameControl(): AbstractControl { return this.formGroup.get('one.name'); }
...
}
for example if I want a class (style) if the form is dirty, I can do something like:
[class.dirty]="formGroup.dirty"
How can I check if the "one" form is dirty?
You can access the group dirtiness by calling
formGroup.get('one').dirty
That returns the FormGroup as AbstractControl, thus with standard control props accessible.
Angular will automatically adds control class, If form is dirty, you can use that class to style as per your need.
div.ng-dirty{
....
}
For More Information

Access host component in a structural directive

I'm using Angular 5.2.10. Suppose we have the following template:
<mat-form-field *appEntityValidate>
<input
matInput
type="text"
placeholder="Some input">
</mat-form-field>
In EntityValidateDirective, we need to get an instance of MatFormField it's apllied to.
I've tried a solution suggested here, i.e. simply inject MatFormField:
#Directive({
selector: "[appEntityValidate]"
})
export class EntityValidateDirective {
constructor(
private readonly matFormField: MatFormField
) {
const dfg = 0;
}
}
, but I'm getting an exception from Angular:
No provider for MatFormField!
Here is Stackblitz.
I suspect that this doesn't work because my directive is structural one rather than an attribute one.
So, how to access host component in a structural directive then?
UPDATE: In attempt to address concern raised by #yurzui in comments. Specifically, that MatFormField isn't really a host component in this case, since the above markup gets de-sugarized into something like this:
<ng-template appEntityValidate>
<mat-form-field>
<input matInput type="text" placeholder="Some input">
</mat-form-field>
</ng-template>
Thus, MatFormField becomes a child of the element which EntityValidateDirective is applied to.
To cover this, I've also tried the following:
#Directive({
selector: "[appEntityValidate]"
})
export class EntityValidateDirective implements AfterContentInit, AfterViewInit {
#ContentChild(MatFormField) content;
#ViewChild(MatFormField) view;
public ngAfterViewInit() {
const view = this.view;
}
public ngAfterContentInit() {
const content = this.content;
}
}
But both content and view are undefined in the corresponding lifecycle hook methods.

check if emails match on blur

I'm trying to check if email field and confirm email field match each other. That is, the user types in their email and then they have to confirm it again. I want the match/validation to happen on blur (when the user presses enter or the textfield loses focus).
Here's my ts file:
import {Component, OnInit} from '#angular/core';
import {User} from './user.interface';
import {FormBuilder, FormGroup, ValidatorFn} from '#angular/forms';
#Component({
selector: 'my-email',
templateUrl: '/app/components/profile/email.component.html',
styleUrls:['styles.css'],
})
export class EmailComponent implements OnInit {
public user : User;
Form : FormGroup;
ngOnInit() {
// initialize model here
this.user = {
Email: '',
confirmEmail: ''
}
if(this.Form.valid) {
this.displayErrors = false;
}
}
constructor(fb: FormBuilder, private cookieService: CookieService, private router: Router) {
this.Form = fb.group({
email: [''],
confirmEmail: ['']
},
{
validator: this.matchingEmailsValidator('email', 'confirmEmail')
});
}
save(model: User, isValid: boolean) {
// call API to save customer
//save email
}
matchingEmailsValidator(emailKey: string, confirmEmailKey: string): ValidatorFn {
return (group: FormGroup): {[key: string]: any} => {
let email = group.controls[emailKey];
let confirmEmail = group.controls[confirmEmailKey];
if (email.value !== confirmEmail.value) {
return {
mismatch: true
};
}
};
}
}
Here's my view:
<form [formGroup]="Form" novalidate (ngSubmit)="Form.valid && save(Form.value, Form.valid)">
<div class="container-fluid">
<div id = "container" class="contain" style="text-align: center">
<div>
<fieldset class="form-group">
<label id = "rounded" class="item item-input .col-md-6 .col-md-offset-3">
<input class="email-address-entry form-control" name="email" type="email" placeholder="name#domain.com" formControlName="email" pattern="^(\\w|[0-9.!#$%&’*+/=?^_\`{|}~-])+#(\\w|[0-9-])+(?:‌​[.](\\w|[0-9-])+)*$"/>
</label>
<p class="Reenter-your-email">Reenter your email to confirm</p>
<label id = "rounded" class="item item-input">
<input class="email-address-entry form-control" (blur)="displayErrors=true" name="confirmEmail" type="email" placeholder="name#domain.com" formControlName="confirmEmail" validateEqual="email"/>
</label>
</fieldset>
</div>
<div>
<label class="entry-invalid">
<p *ngIf="displayErrors && !Form.get('email').valid">The email you entered does not match.</p>
</label>
</div>
<div (click)="Form.get('email').length > 0 ? save(Form.value, Form.valid) : NaN" class="{{ Form.get('email').length > 0 ? 'container-fluid anchorBottomHighlight' : 'container-fluid anchorBottom'}}">
<label class="footerLabel">Confirm</label>
</div>
</div>
</div>
</form>
Currently, with the way it's set up, the validation occurs but it does not get cleared when the correct match is input. I'm wondering how I can setup my view correctly? So the validation message is shown/hidden when the correct match is set and not.
Also it seems like Form.get('email').length > 0 is never greater than 0 / never hit, so my label doesn't toggle to be clickable.
I'm using Angular 2 and reactive forms.
It looks that you're mixing the two form syntaxes: template-driven forms and model-driven forms.
Since you're declaring a form model in your class with FormBuilder, I'm assuming you want a model-driven form.
This means your fields don't need attributes like [(ngModel)] or #EmailAddress.
Instead of that:
<input type="email" [(ngModel)]="user.EmailAddress" required #EmailAddress="ngModel">
Write this:
<!-- Now I'm using `formControlName` to bind the field to the model -->
<!-- Its value must match one of the names you used in the FormBuilder -->
<input type="email" formControlName="email">
ALL of your validators must be declared in the FormBuilder. Not just matchingEmailsValidator, but also required:
this.Form = fb.group({
email: ['', Validators.required],
confirmEmail: ['', Validators.required]
},
{
validator: this.matchingEmailsValidator('email', 'confirmEmail')
});
Now you can access a field with the following syntax:
// In the class
this.Form.get('email').value
this.Form.get('email').errors
<!-- In the template -->
{{ Form.get('email').value }}
{{ Form.get('email').errors }}
You can use these syntaxes to display errors. For example:
<input type="email" formControlName="email">
<p *ngIf="Form.get('email').dirty && Form.get('email').errors.required">
This field is required.
</p>
In the example above, I am displaying an error message if the email field has been touched (i.e. the user tried to enter something) AND the required error is present.
You can also verify that your validation rules are enforced by inspecting the form's markup with your browser's dev tools. Angular should have added classes like .ng-invalid or .ng-valid to the <input> tags that have validation rules.
Finally, regarding your question to check email match on blur. You can't postpone Angular's validation, it will happen in real-time (as the user types). But you could wait for the blur event to display errors.
Combining this last advice with my previous example, here's how you could should an error if the email field is empty AND it has lost focus (blur event):
<input type="email" formControlName="email" (blur)="displayErrors=true">
<p *ngIf="displayErrors && Form.get('email').dirty && Form.get('email').errors.required">
This field is required.
</p>
UPDATE(01-FEB-2017) after Euridice posted this Plunkr:
You still have wayyyyy to much validation code in your template. Like I said, ALL VALIDATORS should be declared IN THE FORM MODEL (with the FormBuilder). More specifically:
The pattern="..." attribute in the email field should be replaced with Validators.pattern() in the form model.
What is the validateEqual="email" attribute in the confirmEmail field? You're not using that anywhere.
The main problem is your test to display the error message: *ngIf="displayErrors && !Form.get('email').valid && Form.get('email').error.mismatch".
First of all, the property is errors with an "s", not error.
Also, your custom validator is setting the error on the form itself, NOT on the email field. This means you should retrieve your mismatch custom error from Form.errors.mismatch, NOT Form.get('email').errors.mismatch.
Here's the updated, working Plunkr: https://plnkr.co/edit/dTjcqlm6rZQxA7E0yZLa?p=preview