使用場景
- message是一個全局組件,當(dāng)使用的時候。并不希望要在模板里添加message模板。
- 希望可以通過類似的代碼來做到如此效果。
this.messageService.error('test1')來顯示一個message
實現(xiàn)的步驟
- 方法一( 最不好用)
通過依賴注入的document https://angular.cn/api/common/DOCUMENT獲取document,然后通過淳樸的dom操作來添加message. - 方法2(實裝起來比較繁瑣,而且不夠自動化)
在根組件里依賴注入ViewContainerRef,然后把ViewContainerRef注冊到message服務(wù)里去。后面調(diào)用message服務(wù)時,相當(dāng)于動態(tài)添加組件。https://angular.cn/guide/dynamic-component-loader - 方法3 (參考的ng-zorro https://ng.ant.design/components/message/zh)
此方法夠自閉,不會污染其他頁面代碼。但是實現(xiàn)比上面麻煩。- 首先得獲取applicationRef https://angular.cn/api/core/ApplicationRef
- 構(gòu)建一個容器,把容器視圖掛載到applicationRef上
- 后面的顯示message相當(dāng)于添加視圖到這個容器里
- 具體實現(xiàn)看https://github.com/NG-ZORRO/ng-zorro-antd/blob/master/components/message/nz-message-base.service.ts