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
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
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
I have a form on my page and when I call FormGroup.reset() it sets the forms class to ng-pristine ng-untouched but FormControl.hasError(...) still returns truthy. What am I doing wrong here?
Template
<form [formGroup]="myForm" (ngSubmit)="submitForm(myForm)">
<mat-form-field>
<input matInput formControlName="email" />
<mat-error *ngIf="email.hasError('required')">
Email is a required feild
</mat-error>
</mat-form-field>
<mat-form-field>
<input matInput type="password" formControlName="password" />
<mat-error *ngIf="password.hasError('required')">
Password is a required feild
</mat-error>
</mat-form-field>
<button type="submit">Login</button>
</form>
Component
export class MyComponent {
private myForm: FormGroup;
private email: FormControl = new FormContorl('', Validators.required);
private password: FormControl = new FormControl('', Validators.required);
constructor(
private formBuilder: FormBuilder
) {
this.myForm = formBuilder.group({
email: this.email,
password: this.password
});
}
private submitForm(formData: any): void {
this.myForm.reset();
}
}
Plunker
https://embed.plnkr.co/Hlivn4/
It (FormGroup) behaves correctly. Your form requires username and password, thus when you reset the form it should be invalid (i.e. form with no username/password is not valid).
If I understand correctly, your issue here is why the red errors are not there at the first time you load the page (where the form is ALSO invalid) but pop up when you click the button. This issue is particularly prominent when you're using Material.
AFAIK, <mat-error> check the validity of FormGroupDirective, not FormGroup, and resetting FormGroup does not reset FormGroupDirective. It's a bit inconvenient, but to clear <mat-error> you would need to reset FormGroupDirective as well.
To do that, in your template, define a variable as such:
<form [formGroup]="myForm" #formDirective="ngForm"
(ngSubmit)="submitForm(myForm, formDirective)">
And in your component class, call formDirective.resetForm():
private submitForm(formData: any, formDirective: FormGroupDirective): void {
formDirective.resetForm();
this.myForm.reset();
}
GitHub issue: https://github.com/angular/material2/issues/4190
In addition to Harry Ninh's solution, if you'd like to access the formDirective in your component without having to select a form button, then:
Template:
<form
...
#formDirective="ngForm"
>
Component:
import { ViewChild, ... } from '#angular/core';
import { NgForm, ... } from '#angular/forms';
export class MyComponent {
...
#ViewChild('formDirective') private formDirective: NgForm;
constructor(... )
private someFunction(): void {
...
formDirective.resetForm();
}
}
After reading the comments this is the correct approach
// you can put this method in a module and reuse it as needed
resetForm(form: FormGroup) {
form.reset();
Object.keys(form.controls).forEach(key => {
form.get(key).setErrors(null) ;
});
}
There was no need to call form.clearValidators()
Add the property -
#ViewChild(FormGroupDirective) formGroupDirective: FormGroupDirective;
and use this instead of this.myForm.reset();
this.formGroupDirective.resetForm();
This will reset the error display and also do the job of form.reset(). But the form, along with the fields, will still show ng-invalid class
Check this answer for more details - https://stackoverflow.com/a/56518781/9262627
The below solution works for me when trying to reset specific form controller in form group -
this.myForm.get('formCtrlName').reset();
this.myForm.get('formCtrlName').setValidators([Validators.required, Validators.maxLength(45), Validators.minLength(4), Validators.pattern(environment.USER_NAME_REGEX)]);
this.myForm.get('formCtrlName').updateValueAndValidity();
form.reset() won't work on custom form control like Angular Material that's why the function is not working as expected.
My workaround for this is something like this
this.form.reset();
for (let control in this.form.controls) {
this.form.controls[control].setErrors(null);
}
this.form.reset() the issue with this is that it will reset your formcontrol values but not the errors so you need to reset them individually by this line of code
for (let control in this.form.controls) {
this.form.controls[control].setErrors(null);
}
With this you don't need to use FormGroupDirective which is a cleaner solution for me.
Github issue: https://github.com/angular/angular/issues/15741
I found that after calling resetForm() and reset(), submitted was not being reset and remained as true, causing error messages to display. This solution worked for me. I found it while looking for a solution to calling select() and focus() on an input tag, which also wasn't working as expected. Just wrap your lines in a setTimeout(). I think setTimeout is forcing Angular to detect changes, but I could be wrong. It's a bit of a hack, but does the trick.
<form [formGroup]="myFormGroup" #myForm="ngForm">
…
<button mat-raised-button (click)="submitForm()">
</form>
submitForm() {
…
setTimeout(() => {
this.myForm.resetForm();
this.myFormGroup.reset();
}, 0);
}
resetForm() {
this.myFormGroup.reset();
this.myFormGroup.controls.food.setErrors(null);
this.myFormGroup.updateValueAndValidity();
}
UPDATE FROM 2021 - ANGULAR 11.2
The fact to use a [formGroup]="form and a #formDirective="ngForm" directly into the HTML function is not a good practise. Or maybe you would prefer to use #ViewChild, and do it directly from your .ts. Actually, the problem don't come from Angular, but Material.
If you take a look at their GitHub, you will see this :
/** Provider that defines how form controls behave with regards to displaying error messages. */
#Injectable({providedIn: 'root'})
export class ErrorStateMatcher {
isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
return !!(control && control.invalid && (control.touched || (form && form.submitted)));
}
}
The form will keep its submitted state. So you just have to delete the last part of the function.
Here is my solution (tested and working). I have a Material Module, into I've implemented this :
export class ShowOnInvalidTouchedErrorStateMatcher implements ErrorStateMatcher {
isErrorState(control: FormControl): boolean {
return !!(control && control.invalid && control.touched);
}
}
#NgModule({
providers: [
{
provide: ErrorStateMatcher, useClass: ShowOnInvalidTouchedErrorStateMatcher
}
],
exports: [
MatSnackBarModule,
MatTabsModule,
...
]
});
If you want to use this ErrorStateMatcher on only one form, it's possible. Please see this Material example. This is the same principle.
I had no luck with resetting the form directive. But You can also change the input state to pending to do that as well.
this.myForm.get("email").reset();
this.myForm.get("password").reset();
To anyone whom this may help, I am running Angular 9.1.9 and I didn't want to reset the form/controls just the overall validity of the form so I just ran:
this.registerForm.setErrors(null);
...where registerForm: FormGroup and that reset the form errors, leading to:
this.registerForm.valid
...returning true.
The same can be done for controls:
this.registerForm.get('email').setErrors(null)
As soon as the form is touched, these errors are re-evaluated anyway so if that's not good enough, you may need to have a boolean flag to further pin-down exactly when you want to start showing/hiding error UI.
I did not need to touch the directive in my case.
I was also having the same set of problems. My problem was that i was using mat-form-field and formGroup. After resetting the form submitted flag was not resetting.
So, the solution that worked for me is, putting a directive of ngForm along with formGroup and passing onSubmit(form). Added
#ViewChild('form') form;
in component and then I used
this.form.resetForm();
Nothing from above worked for me (Angular 7.2, Angular Material 7.3.7).
Try to pass with submit method an event on view:
<form [formGroup]="group" (ngSubmit)="onSubmit($event)">
<!-- your form here -->
</form>
Then use it to reset currentTarget and your form afterwards:
public onSubmit(event): void {
// your code here
event.currentTarget.reset()
this.group.reset()
}
Simple fix: use button with type="reset" and function submitForm() together
<form [formGroup]="MyForm" (ngSubmit)="submitForm()">
<input formControlName="Name">
<mat-error>
<span *ngIf="!tunersForm.get('Name').value && tunersForm.get('Name').touched"></span>
</mat-error>
<button type="reset" [disabled]="!MyForm.valid" (click)="submitForm()">Save</button>
</form>
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.