From 5df007923e7724e6473e029280b838f6dd5feed9 Mon Sep 17 00:00:00 2001 From: Kristiyan Kostadinov Date: Tue, 31 Aug 2021 21:58:14 +0200 Subject: [PATCH] fix(material/select): show required asterisk when using required validator Similar to #23362. Fixes that the required asterisk wasn't being shown when a select is required. --- .../mdc-select/select.spec.ts | 8 +++++++- src/material/select/select.spec.ts | 4 ++++ src/material/select/select.ts | 14 +++++++++++--- 3 files changed, 22 insertions(+), 4 deletions(-) diff --git a/src/material-experimental/mdc-select/select.spec.ts b/src/material-experimental/mdc-select/select.spec.ts index d4162aa126e0..c853f3a99522 100644 --- a/src/material-experimental/mdc-select/select.spec.ts +++ b/src/material-experimental/mdc-select/select.spec.ts @@ -2844,6 +2844,11 @@ expect(panel.scrollTop) subscription.unsubscribe(); })); + it('should set an asterisk after the label if the FormControl is required', fakeAsync(() => { + const label = fixture.nativeElement.querySelector('.mat-mdc-form-field label'); + expect(label.classList).toContain('mdc-floating-label--required'); + })); + }); describe('with custom error behavior', () => { @@ -4539,7 +4544,8 @@ class InvalidSelectInForm { template: `
- + Food + {{option.viewValue}} diff --git a/src/material/select/select.spec.ts b/src/material/select/select.spec.ts index ad5675e78256..dda499b6fc0a 100644 --- a/src/material/select/select.spec.ts +++ b/src/material/select/select.spec.ts @@ -2911,6 +2911,10 @@ describe('MatSelect', () => { subscription.unsubscribe(); })); + it('should set an asterisk after the label if the FormControl is required', fakeAsync(() => { + expect(fixture.nativeElement.querySelector('.mat-form-field-required-marker')).toBeTruthy(); + })); + }); describe('with custom error behavior', () => { diff --git a/src/material/select/select.ts b/src/material/select/select.ts index ecd4a4db7916..c744bf94355e 100644 --- a/src/material/select/select.ts +++ b/src/material/select/select.ts @@ -59,7 +59,13 @@ import { ViewChild, ViewEncapsulation, } from '@angular/core'; -import {ControlValueAccessor, FormGroupDirective, NgControl, NgForm} from '@angular/forms'; +import { + ControlValueAccessor, + FormGroupDirective, + NgControl, + NgForm, + Validators, +} from '@angular/forms'; import { _countGroupLabelsBeforeOption, _getOptionScrollPosition, @@ -317,12 +323,14 @@ export abstract class _MatSelectBase extends _MatSelectMixinBase implements A /** Whether the component is required. */ @Input() - get required(): boolean { return this._required; } + get required(): boolean { + return this._required ?? this.ngControl?.control?.hasValidator(Validators.required) ?? false; + } set required(value: boolean) { this._required = coerceBooleanProperty(value); this.stateChanges.next(); } - private _required: boolean = false; + private _required: boolean | undefined; /** Whether the user should be allowed to select multiple options. */ @Input()