Skip to content

docs(material/form-field): Update example to not call function in template #28748

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions pkg-externals.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ PKG_EXTERNALS = [
"@angular/common/http/testing",
"@angular/common/testing",
"@angular/core",
"@angular/core/rxjs-interop",
"@angular/core/testing",
"@angular/forms",
"@angular/platform-browser",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
<div class="example-container">
<mat-form-field>
<mat-label>Enter your email</mat-label>
<input matInput placeholder="pat@example.com" [formControl]="email" required>
<input matInput
placeholder="pat@example.com"
[formControl]="email"
(blur)="updateErrorMessage()"
required>
@if (email.invalid) {
<mat-error>{{getErrorMessage()}}</mat-error>
<mat-error>{{errorMessage}}</mat-error>
}
</mat-form-field>
</div>
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import {Component} from '@angular/core';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
import {FormControl, Validators, FormsModule, ReactiveFormsModule} from '@angular/forms';
import {MatInputModule} from '@angular/material/input';
import {MatFormFieldModule} from '@angular/material/form-field';
import {merge} from 'rxjs';

/** @title Form field with error messages */
@Component({
Expand All @@ -14,11 +16,21 @@ import {MatFormFieldModule} from '@angular/material/form-field';
export class FormFieldErrorExample {
email = new FormControl('', [Validators.required, Validators.email]);

getErrorMessage() {
errorMessage = '';

constructor() {
merge(this.email.statusChanges, this.email.valueChanges)
.pipe(takeUntilDestroyed())
.subscribe(() => this.updateErrorMessage());
}

updateErrorMessage() {
if (this.email.hasError('required')) {
return 'You must enter a value';
this.errorMessage = 'You must enter a value';
} else if (this.email.hasError('email')) {
this.errorMessage = 'Not a valid email';
} else {
this.errorMessage = '';
}

return this.email.hasError('email') ? 'Not a valid email' : '';
}
}