Использование значков материалов с md-icon в Angular Material 2

Я не могу заставить md-icon отображать значки из материалов Google. Для тех, кому не нужно много пояснений, вот код, более подробная информация после кода.

app.component (где я отображаю все свои основные компоненты, фактическая иконка md находится в header.component):

import { Component } from '@angular/core';
import { HeaderComponent } from './shared/header.component';
import { ContentComponent } from './shared/content.component';
import { FooterComponent } from './shared/footer.component';

@Component({
    selector: 'my-app',
    template: `<div id="wrapper">
    <header></header>
    <content></content>
    <footer></footer>
  <div>`,
     directives: [HeaderComponent, ContentComponent, FooterComponent]
})
export class AppComponent { }

Компонент заголовка (где я пытаюсь вызвать md-icon):

import { Component } from '@angular/core';
import {MdIcon} from '@angular2-material/icon';

@Component({
    selector: 'header',
    template: `<md-icon>home</md-icon>
    <h1>This is the Header</h1>
    `,
    directives: [MdIcon]
})
export class HeaderComponent { }

а вот css и html в соответствии с шагами на сайте материалов Google для использования их значков:

CSS:

@font-face {
  font-family: 'Material Icons';
  font-style: normal;
  font-weight: 400;
  src: url("../fonts/MaterialIcons-Regular.eot");
  /* For IE6-8 */
  src: local("Material Icons"), local("MaterialIcons-Regular"), url("../fonts/MaterialIcons-Regular.woff2") format("woff2"), url("../fonts/MaterialIcons-Regular.woff") format("woff"), url("../fonts/MaterialIcons-Regular.ttf") format("truetype");
}
.material-icons {
  font-family: 'Material Icons';
  font-weight: normal;
  font-style: normal;
  font-size: 24px;
  /* Preferred icon size */
  display: inline-block;
  line-height: 1;
  text-transform: none;
  letter-spacing: normal;
  word-wrap: normal;
  white-space: nowrap;
  direction: ltr;
  /* Support for all WebKit browsers. */
  -webkit-font-smoothing: antialiased;
  /* Support for Safari and Chrome. */
  text-rendering: optimizeLegibility;
  /* Support for Firefox. */
  -moz-osx-font-smoothing: grayscale;
  /* Support for IE. */
  font-feature-settings: 'liga';
}

HTML:

<html>

<head>
  <title>Boiler Plate</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="assets/styles/layout.css">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <!-- 1. Load libraries -->
  <!-- Polyfill(s) for older browsers -->
  <script src="node_modules/core-js/client/shim.min.js"></script>
  <script src="node_modules/zone.js/dist/zone.js"></script>
  <script src="node_modules/reflect-metadata/Reflect.js"></script>
  <script src="node_modules/systemjs/dist/system.src.js"></script>
  <!-- 2. Configure SystemJS -->
  <script src="systemjs.config.js"></script>
  <script>
    System.import('app').catch(function(err) {
      console.error(err);
    });
  </script>
</head>
<!-- 3. Display the application -->

<body>
  <my-app>Loading...</my-app>
</body>

</html>

Первоначально я не получал никаких ошибок, он просто отображал md-значок как «дом» в виде обычного текста. Однако я думаю, что мне не хватало директивы для MdIcon, поэтому я вставил ее, и теперь я получаю эту ошибку «Нет провайдера для MdIconRegistry!». Они немного говорят о MdIconRegistry в своих документах, но из как я это читаю, вам это нужно только в том случае, если вы не хотите использовать стандартные значки Google, которые я хочу использовать. Итак, в основном я импортировал компонент, включил директиву, добавил ссылку в свой индекс и добавил код CSS в свои таблицы стилей. Из того, что я прочитал, это должно работать, но я явно что-то упускаю.

Любая помощь будет оценена по достоинству, и если у кого-то есть критические замечания по коду, не связанному с фактическим вопросом, пожалуйста, дайте мне знать, я очень новичок в Angular 2, и я мог бы использовать все советы, которые я могу получить.

Заранее спасибо.


person Colton Williams    schedule 26.05.2016    source источник


Ответы (3)


Итак, я нашел то, что мне не хватало, это было в документах, я просто искал не в том месте. Внутри вашего файла main.ts вам нужно импортировать и загружать HTTP_Providers, а внутри вашего компонента вам нужно импортировать MdIcon и MdIconRegistry, а также включить поставщика для MdIconRegistry. Что все это значит? Я рад, что вы спросили!

Main.ts до:

import { bootstrap }    from '@angular/platform-browser-dynamic';
import { AppComponent } from './app.component';

bootstrap(AppComponent);

Main.ts после:

import { bootstrap }    from '@angular/platform-browser-dynamic';
import { AppComponent } from './app.component';
import { HTTP_PROVIDERS } from '@angular/http';

bootstrap(AppComponent, [
    HTTP_PROVIDERS
]);

header.component.ts до:

import { Component } from '@angular/core';
import {MdIcon} from '@angular2-material/icon';

@Component({
    selector: 'header',
    template: `<md-icon>home</md-icon>`,
    directives: [MdIcon]
})
export class HeaderComponent { }

header.component.ts после:

import { Component } from '@angular/core';
import {MdIcon, MdIconRegistry} from '@angular2-material/icon';

@Component({
    selector: 'header',
    template: `<md-icon>home</md-icon>`,
    directives: [MdIcon],
    providers: [MdIconRegistry]
})
export class HeaderComponent { }

Документацию по значкам можно найти здесь, а также документацию, которая помогли мне, можно найти здесь в самом низу.

person Colton Williams    schedule 26.05.2016

Правильный ответ здесь: вы должны правильно настроить проект. Вы неправильно импортируете иконки. Вам не нужно ничего делать, кроме как импортировать значки и шрифты.

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

Вы импортируете это в html и ничего больше. Все, что вы сделали, было странным обходным путем.

person Michael Jota    schedule 15.11.2016

Из документации:

<!--
For Material Design Icons
The class '.material-icons' is auto-added if a style has NOT been specified
since `material-icons` is the default fontset. So your markup:
-->
<md-icon> face </md-icon>
<!-- becomes this at runtime: -->
<md-icon md-font-set="material-icons"> face </md-icon>
<!-- If the fontset does not support ligature names, then we need to use the ligature unicode.-->
<md-icon>  </md-icon>
<!-- The class '.material-icons' must be manually added if other styles are also specified-->
<md-icon class="material-icons md-light md-48"> face </md-icon>
person MayK    schedule 26.05.2016
comment
Документация взята из Angular Material 1, проблема связана с материалом Angular 2, это моя вина, хотя я пометил его как angular-material2, так и angular-material. Я собираюсь удалить тег angular-material, извините за путаницу. (Я попробовал ваше предложение на всякий случай, но не повезло) - person Colton Williams; 26.05.2016