Show valid email address on the angular prompt - html

I have created a temporary password email which any user can get once they click on the forgot password feature. After getting the temp pass they will see a prompt asking them to enter that temp pass. I want to show the same valid email address they have used or associated with the account they have on the angular prompt or pop-up text box. Currently I have created a prompt where I am not able to show the email, since I have not used it before.
My concern is how can I trigger the email address so that it will be visible on that pop-up prompt?
email address as an example: abcd#yahoo.com
I know how to use the <a> tag using href="" for the backend to share hyperlinks, but I'm not familiar how to show or how to trigger any email link on an angular prompt.
Below codes are what I have for the .html and the .ts files.
temporary.component.ts
tempPasswordTextLbl: "We have sent a temp pass to the abcd#yahoo.com email you provided. Please enter it below.",
temporary.component.html
<p style="margin: 30px; text-align: justify; font-size:15px;">{{header.oneTimePasswordMessageLbl?header.oneTimePasswordMessageLbl:headerText.oneTimePasswordMessageLbl}}</p>
Below is the image of the prompt and the email should show up as shown in the screenshot:

As I understood it, first you need to check if the email is valid and only then show the popup informing that the code was sent to the email previously informed.
For this you need to use FormBuilder, FormGroup and Validators
html
<div class="jumbotron">
<div class="container">
<div class="row">
<div class="col-md-6 offset-md-3">
<h3>Angular Form Validation</h3>
<form [formGroup]="myregisterForm" (ngSubmit)="onSubmit()">
<div class="form-group">
<label>Email: {{ myEmail }}</label>
<input
type="text"
[(ngModel)]="myEmail"
formControlName="email"
class="form-control"
[ngClass]="{ 'is-invalid': submitted && f.email.errors }"
/>
<div *ngIf="submitted && f.email.errors" class="invalid-feedback">
<div *ngIf="f.email.errors.required">Email is required</div>
<div *ngIf="f.email.errors.email">
Email must be a valid email address
</div>
</div>
</div>
<div class="form-group">
<button class="btn btn-primary">Save</button>
</div>
</form>
</div>
</div>
</div>
</div>
ts
import { Component, OnInit } from '#angular/core';
import { FormBuilder, FormGroup, Validators } from '#angular/forms';
#Component({
selector: 'app',
templateUrl: 'app.component.html',
})
export class AppComponent implements OnInit {
myregisterForm: FormGroup;
submitted = false;
myEmail = ''; // need to use text interpolation in html
constructor(private formBuilder: FormBuilder) {}
ngOnInit() {
this.myregisterForm = this.formBuilder.group({
email: [
'',
[
Validators.required,
Validators.email,
Validators.pattern('^[a-z0-9._%+-]+#[a-z0-9.-]+\\.[a-z]{2,4}$'),
],
],
});
}
// convenience getter for easy access to form fields
get f() {
return this.myregisterForm.controls;
}
onSubmit() {
this.submitted = true;
// stop here if form is invalid
if (this.myregisterForm.invalid) {
return;
}
alert(
'We have sent the temp pass to: ' + this.myEmail + ' email you provided'
);
}
}
See working example on Stackblitz

Related

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

Angular 7 components: how to detect a change by user interaction?

I have a component with several checkboxes, drop-downs, and a save button.
Here is a simplified example component template:
<aside class="container">
<div class="row">
<input
type="checkbox"
id="all-users"
[(ngModel)]="showAllUsers"
(ngModelChange)="onChange($event)"
/>
<label for="all-users">Show all users</label>
</div>
<div class="row">
<ng-select
[(ngModel)]="selectedUser"
[clearable]="false"
appendTo="body"
(change)="onChange($event)"
>
<ng-option *ngFor="let user of activeUsers" [value]="user">{{ user }}</ng-option>
</ng-select>
</div>
<div class="row">
<button type="button" class="btn btn-primary" [disabled]="!dirty" (click)="onSave()">
Save Changes
</button>
</div>
</aside>
I want to enable the Save Changes button only when the user made a change, either by unchecking the check-box or changing a selection in drop-down box.
Right now I have an event handler registered at each and every control in the component (the onChange function in the example above), and use a dirty flag to disable or enable the Save Changes button.
Here is the component.ts for the above template:
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-filter',
templateUrl: './filter.component.html',
styleUrls: ['./filter.component.css']
})
export class FilterComponent implements OnInit {
dirty: boolean;
showAllUsers: boolean;
selectedUser: string;
activeUsers: string[];
ngOnInit() {
this.dirty = false;
this.showAllUsers = true;
this.activeUsers = ['Thanos', 'Thor', 'Starlord'];
this.selectedUser = 'Thor';
}
onChange(event) {
console.log('Event is ' + event);
this.dirty = true;
}
onSave() {
console.log('Gonna save changes...');
this.dirty = false;
}
}
Registering the event handler to every control does not seem intuitive to me.
Is this the correct approach to figure out a change made by user or does angular provide a different way to achieve this?
I would highly recommand using both FormGroup and FormControl to achieve this behavior.
Both exposes the dirty property, a read-only boolean.
The dirty property is set to true when the user changes the value of the FormControl from the UI. In the case of the FormGroup, the dirty property is set to true as long as at least 1 of the FormControl in that group is dirty.
As a side note, the property pristine is the opposite property. So you can use one or the other if it simplifies the condition.
[disabled]="myFormGroup.pristine" might be easier to read than [disabled]="!myFormGroup.dirty".

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

Angular 2 Form "Cannot Find Control"

I am trying to use Angular 2 Forms for validation, but when I try to add more than one control. It seems like it just gets ignored. I have followed many different guides to see how everyone else does it, but none of those ways seem to work.
What I have been doing is this in my template:
<form [formGroup]="form" novalidate (ngSubmit)="save(form.valid)">
<div class="row" id="message-wrapper">
<label>Message</label>
<small [hidden]="form.controls.message.valid || (form.controls.message.pristine && !submitted)">
Message is required (minimum 10 characters).
</small>
<textarea
class="textarea-scaled"
type="text"
[(ngModel)]="campaign.message"
formControlName="message"
placeholder="This will be sent out by supporters with a URL back to this campaign">
</textarea>
</div>
<div class="row" id="promo-wrapper">
<label>Promotion: </label>
<small [hidden]="form.controls.promotion.valid ||(form.controls.promotion.pristine && !submitted)">
Promotion is required and should be between 10 and 100 characters
</small>
<textarea
class="textarea-scaled"
type="text"
[(ngModel)]="campaign.promotion"
formControlName="promotion"
placeholder="What would you like to be sent out in promotional messages?">
</textarea>
</div>
</form>
Then in my component I do this:
form: FormGroup;
constructor(private builder: FormBuilder,
private _dataservice: DataService) {
this.form = builder.group({
"message": ['', [Validators.required, Validators.minLength(10)]],
"promotion": ['', [Validators.required, Validators.minLength(10)]]
});
}
But I keep getting a "Cannot find control 'promotion'" console error...
Any help will be appreciated!
This may not be the answer to the original question, but this may be useful if you jumped here from google.
You need to check these things.
You must have a "name" attribute for all the controls which has [ngModel]
If you exclude some fields from validation, then add [ngModelOptions]="{standalone: true}" (remember the first rule, still you need a "name")
Make sure you have formControlName attribute for the controls that you are going to validate. (remember the first rule)
I tried to create new FormGroup in my component.
I've imported ReactiveFormsModule from angular/forms and added to app.module.ts imports.
but I was getting Cannot find name 'FormGroup' and Cannot find name 'FormControl' errors
Here is my component
export class SignupFormComponent {
form1 = new FormGroup({
username: new FormControl(),
password: new FormControl()
});
}
Adding the below import statement in component resolved my issue.
import { FormGroup, FormControl } from '#angular/forms';
Not the answer to your question but Posting as this might help someone who faces same error.

form validation in angular 2

I am writing a form validation in angular2.
my error is Cannot read property 'valid' of undefined
My HTML file contains a form i.e.
<form id="commentform" class="comment-form" novalidate
[ngFormModel] = "contact" (ngSubmit)="submit(contact.value)">
<div class="form-input">
<input type="text" id="author" name="author" placeholder="Name *" value=""
[ngFormControl] = "contact.controls['author']" pattern="[a-zA-Z ]*"/>
<div [hidden]="author.valid">Name is required
</div>
</div>
I am getting error at div [hidden]="author.valid".
The error is Cannot read property 'valid' of undefined"
My component file contains
import {FormBuilder ,ControlGroup,Validators } from '#angular/common';
#Component({
selector: 'my-contact',
templateUrl : 'app/contact.html'
}
export class ContactComponent {
contact : ControlGroup;
constructor(private _OnChange:OnChange,private _formBuilder : FormBuilder){
this.ngAfterViewInit();
}
ngOnInit() : any{
this.contact = this._formBuilder.group({
'author' : ['',Validators.required] }); }
submit(){
console.log(JSON.stringify(this.contact.value));
}
Use
[hidden]="contact.controls['author'].valid"
Because author is not a variable. Use
<div [hidden]="contact?.controls?.author?.valid">Name is required</div>
Actually, even better. you should use the new forms module #angular/forms
https://scotch.io/tutorials/using-angular-2s-model-driven-forms-with-formgroup-and-formcontrol