Angular Material Icon使用
1. 引入圖示資源
在專案index.html檔案裡新增icon的圖示庫檔案的引用。
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
2. 匯入MatIconModule
如果需要在別的元件同樣使用,則需要exports裡面引出.
3. icons 資源
可以訪問material design獲取全部icon名稱及圖示樣式資訊。
4. 自定義svg圖示資源
- 在網上下載svg資源,並將檔案儲存到專案assets目錄裡。
-
註冊圖示資源
註冊圖示資源需要用到:
MatIconRegistry 以及 DomSanitizer 類。
MatIconRegistry(圖示資源是基於字型而不是圖片的)
使用MatIconRegistry的下面方法addSvgIcon,addSvgIconInNamespace, addSvgIconLiteral 或者addSvgIconLiteralInNamespace 註冊.
DomSanitizer 可以把值淨化為在不同 DOM 上下文中的安全內容,來幫你防範跨站指令碼攻擊(XSS)類的安全問題。
abstract class DomSanitizer implements Sanitizer { abstract sanitize(context: SecurityContext, value: SafeValue | string | null): string | null abstract bypassSecurityTrustHtml(value: string): SafeHtml abstract bypassSecurityTrustStyle(value: string): SafeStyle abstract bypassSecurityTrustScript(value: string): SafeScript abstract bypassSecurityTrustUrl(value: string): SafeUrl abstract bypassSecurityTrustResourceUrl(value: string): SafeResourceUrl }
abstract sanitize(context: SecurityContext, value: SafeValue | string | null): string | null
SecurityContext:列舉
enum SecurityContext { NONE: 0 HTML: 1 STYLE: 2 SCRIPT: 3 URL: 4 RESOURCE_URL: 5 }
SafeValue :一個標記性介面,用於表示一個值可以安全的用在特定的上下文中。
SafeValue 子介面:
- SafeHtml
- SafeResourceUrl
- SafeScript
- SafeStyle
- SafeUrl
如果這個值在這個上下文中是可信的,則該方法會解開所包含的安全值,並且直接使用它;否則,這個值就會根據給定的安全上下文淨化成安全的,比如替換那些具有不安全協議(例如 javascript:)的 URL。 該實現負責確保在給定的上下文中可以絕對安全的使用該值。
其餘函式警告: 使用不可信的使用者資料呼叫此方法將會讓你的應用暴露在 XSS 安全風險之下!
當使用 bypassSecurityTrust... 時,請儘量確保儘早呼叫該方法,並且讓他儘可能接近值的來源,以便能更容易地驗證使用它時有沒有引入安全風險。
這2個類需要DI進元件。
import {MatIconRegistry} from '@angular/material'; import {DomSanitizer} from '@angular/platform-browser'; constructor( iconRegistry:MatIconRegistry ,domSanitizer:DomSanitizer ){ iconRegistry.addSvgIcon('bell',domSanitizer.bypassSecurityTrustResourceUrl('assets/bell.svg')); }
svg匯入需要http支援,因為DomSanitizer 涉及url解析,因此需要匯入httpClientModule。
import { HttpClientModule} from '@angular/common/http' @NgModule({ imports: [ HttpClientModule, ] }) export class AppModule { }