Angular Material Icon (10分でSVGアイコン作成)

SVGアイコン作成

SVG(Scalable Vector Graphics)はベクター画像です。
ベクター画像は、拡大縮小しても画質が劣化しませんが、
Angular Materialで、
SVGアイコンを使用するには制約あります。

動的HTMLページへのユーザー入力に対する、
XSS(クロスサイトスクリプティング)を、
利用した攻撃を防ぐため、
MatIconRegistry 、DomSanitizerサービスを、
使用する 必要があります。
 
コードは
https://material.angular.io/components/icon/examples
SVG iconsから、
app.component.tsにコピー&ペーストします。

app.component.tsのコードは次の様になります。



import {Component} from '@angular/core';
import {DomSanitizer} from '@angular/platform-browser';
import {MatIconRegistry} from '@angular/material/icon';
/**
* @title SVG icons
*/
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'exe-app';

constructor(iconRegistry: MatIconRegistry, sanitizer: DomSanitizer) {
iconRegistry.addSvgIcon(
'thumb_up',
sanitizer.bypassSecurityTrustResourceUrl('assets/thumb_up.svg'));
}
}

'assets/thumb_up.svg' のデイレクトリは、
assets/に注意してください。
thumb_up.svg は簡略化のため名前を変更しています。 次は
app.module.tsに、モジュール
HttpClientModuleを追加します。



import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { CmaterialModule } from './cmaterial.module';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
CmaterialModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

次はSVGアイコンです。
https://material.io/resources/icons/?style=baseline
サイトから、ダウンロードして、
exe-appのsrc/assetsフォルダー格納します。
名前はthumb_up.svgに変更します。

そして、
app.component.htmlにコードを記入します。



<mat-icon svgIcon="thumbs-up" aria-hidden="false" aria-label="thumbs up SVG icon"></mat-icon>

ファイルを保存して、
ng serve コマンドで
http://localhost:4200 を表示します。