@@ -29,15 +29,17 @@ export type AriaLivePoliteness = 'off' | 'polite' | 'assertive';
29
29
30
30
@Injectable ( { providedIn : 'root' } )
31
31
export class LiveAnnouncer implements OnDestroy {
32
- private readonly _liveElement : Element ;
32
+ private readonly _liveElement : HTMLElement ;
33
+ private _document : Document ;
33
34
34
35
constructor (
35
36
@Optional ( ) @Inject ( LIVE_ANNOUNCER_ELEMENT_TOKEN ) elementToken : any ,
36
- @Inject ( DOCUMENT ) private _document : any ) {
37
+ @Inject ( DOCUMENT ) _document : any ) {
37
38
38
- // We inject the live element as `any` because the constructor signature cannot reference
39
- // browser globals (HTMLElement) on non-browser environments, since having a class decorator
40
- // causes TypeScript to preserve the constructor signature types.
39
+ // We inject the live element and document as `any` because the constructor signature cannot
40
+ // reference browser globals (HTMLElement, Document) on non-browser environments, since having
41
+ // a class decorator causes TypeScript to preserve the constructor signature types.
42
+ this . _document = _document ;
41
43
this . _liveElement = elementToken || this . _createLiveElement ( ) ;
42
44
}
43
45
@@ -72,9 +74,17 @@ export class LiveAnnouncer implements OnDestroy {
72
74
}
73
75
}
74
76
75
- private _createLiveElement ( ) : Element {
76
- let liveEl = this . _document . createElement ( 'div' ) ;
77
+ private _createLiveElement ( ) : HTMLElement {
78
+ const elementClass = 'cdk-live-announcer-element' ;
79
+ const previousElements = this . _document . getElementsByClassName ( elementClass ) ;
77
80
81
+ // Remove any old containers. This can happen when coming in from a server-side-rendered page.
82
+ for ( let i = 0 ; i < previousElements . length ; i ++ ) {
83
+ previousElements [ i ] . parentNode ! . removeChild ( previousElements [ i ] ) ;
84
+ }
85
+
86
+ const liveEl = this . _document . createElement ( 'div' ) ;
87
+ liveEl . classList . add ( elementClass ) ;
78
88
liveEl . classList . add ( 'cdk-visually-hidden' ) ;
79
89
liveEl . setAttribute ( 'aria-atomic' , 'true' ) ;
80
90
liveEl . setAttribute ( 'aria-live' , 'polite' ) ;
0 commit comments