From a1a99c0fdb1c76f71255384b36f80d12dd16c2f6 Mon Sep 17 00:00:00 2001 From: Miles Malerba Date: Tue, 19 Mar 2024 20:55:31 +0000 Subject: [PATCH] docs(material/form-field): Update example to not call function in template --- pkg-externals.bzl | 1 + .../form-field-error-example.html | 8 ++++++-- .../form-field-error-example.ts | 20 +++++++++++++++---- 3 files changed, 23 insertions(+), 6 deletions(-) diff --git a/pkg-externals.bzl b/pkg-externals.bzl index bb8f3c657188..24e43fd99b50 100644 --- a/pkg-externals.bzl +++ b/pkg-externals.bzl @@ -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", diff --git a/src/components-examples/material/form-field/form-field-error/form-field-error-example.html b/src/components-examples/material/form-field/form-field-error/form-field-error-example.html index 56c5be722ebf..0c434dd18ac0 100644 --- a/src/components-examples/material/form-field/form-field-error/form-field-error-example.html +++ b/src/components-examples/material/form-field/form-field-error/form-field-error-example.html @@ -1,9 +1,13 @@
Enter your email - + @if (email.invalid) { - {{getErrorMessage()}} + {{errorMessage}} }
diff --git a/src/components-examples/material/form-field/form-field-error/form-field-error-example.ts b/src/components-examples/material/form-field/form-field-error/form-field-error-example.ts index 8993dd35c953..891a4432257e 100644 --- a/src/components-examples/material/form-field/form-field-error/form-field-error-example.ts +++ b/src/components-examples/material/form-field/form-field-error/form-field-error-example.ts @@ -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({ @@ -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' : ''; } }