@@ -29,15 +29,17 @@ export type AriaLivePoliteness = 'off' | 'polite' | 'assertive';
2929
3030@Injectable ( { providedIn : 'root' } )
3131export class LiveAnnouncer implements OnDestroy {
32- private readonly _liveElement : Element ;
32+ private readonly _liveElement : HTMLElement ;
33+ private _document : Document ;
3334
3435 constructor (
3536 @Optional ( ) @Inject ( LIVE_ANNOUNCER_ELEMENT_TOKEN ) elementToken : any ,
36- @Inject ( DOCUMENT ) private _document : any ) {
37+ @Inject ( DOCUMENT ) _document : any ) {
3738
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 ;
4143 this . _liveElement = elementToken || this . _createLiveElement ( ) ;
4244 }
4345
@@ -72,9 +74,17 @@ export class LiveAnnouncer implements OnDestroy {
7274 }
7375 }
7476
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 ) ;
7780
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 ) ;
7888 liveEl . classList . add ( 'cdk-visually-hidden' ) ;
7989 liveEl . setAttribute ( 'aria-atomic' , 'true' ) ;
8090 liveEl . setAttribute ( 'aria-live' , 'polite' ) ;
0 commit comments