Показывает важную информацию на странице. Может содержать подсказку, сигнализировать об изменении статуса или наличии проблемы.

У алертов два размера. Обычный размер используется по умолчанию; передайте [compact]="true" для компактного размера, который применяется в стеснённых местах — поповерах и формах.

Heading
If there is no heading, do not put a period at the end of the last sentence. If the message contains both body text and a heading, put a period at the end of the body text.
Heading
If there is no heading, do not put a period at the end of the last sentence. If the message contains both body text and a heading, put a period at the end of the body text.

По умолчанию алерты оформлены сдержанно и выделяются только цветом иконки. Если блок теряется на экране, то можно привлечь к нему внимание с помощью варианта с цветным фоном.

Default
If there is no heading, do not put a period at the end of the last sentence. If the message contains both body text and a heading, put a period at the end of the body text.
Colored
If there is no heading, do not put a period at the end of the last sentence. If the message contains both body text and a heading, put a period at the end of the body text.

Свойство alertColor задаёт статус: error, warning, success или info (по умолчанию). Оно определяет фон в цветном варианте и автоматически окрашивает спроецированную иконку статуса, у которой не задан явный [color]: иконка окрашивается в соответствующий статусу цвет, кроме info — она окрашивается в contrast. Задайте [color] на иконке сами, чтобы отказаться от автоокраски.

Проецируйте одну иконку статуса. Слот отрисовывает все попавшие в него [kbq-icon] и [kbq-icon-item], но автоматически окрашивает только одну из них — kbq-icon имеет приоритет над kbq-icon-item, — поэтому любая следующая иконка сохранит тот цвет, который ей задали. При проекции обеих разновидностей в режиме разработки ещё и выводится предупреждение.

Information
If there is no heading, do not put a period at the end of the last sentence. If the message contains both body text and a heading, put a period at the end of the body text.
Warning
If there is no heading, do not put a period at the end of the last sentence. If the message contains both body text and a heading, put a period at the end of the body text.
Error
If there is no heading, do not put a period at the end of the last sentence. If the message contains both body text and a heading, put a period at the end of the body text.
Success
If there is no heading, do not put a period at the end of the last sentence. If the message contains both body text and a heading, put a period at the end of the body text.

Блок можно скрыть по кнопке-иконке в углу алерта. Алерт не скрывает себя сам — подпишитесь на событие (closed) (возникает при активации кнопки закрытия) и удалите или скройте алерт в своём коде. Если система сообщает о проблеме, в этом случае алерт отображается постоянно и пользователь не может его закрыть.

The alert is dismissed with the close icon in the corner; do not duplicate this with a button below the message text

В алерте можно расположить ссылки и кнопки, можно отказаться от иконки и заголовка. В объемном оповещении текст можно разбивать на абзацы.

Failed to upload the file
When a hyperlink is at the end of a sentence, the period takes the link color, but is not underlined.
Failed to upload the file
When a hyperlink is at the end of a sentence, the period takes the link color, but is not underlined.
Failed to update the agent ekb-mail-server
Failed to update the agent ekb-mail-server
The module is configured in the policy Hypervisors
The module is configured in the policy Hypervisors
After recovery, check the agent groups' links to policies
After recovery, check the agent groups' links to policies
Short text in the alert
Short text in the alert

A paragraph should convey and develop only one idea. For example, if you mix the causes, the essence of the problem, and possible solutions to the situation you are describing in a single paragraph, the reader will quickly get tired and most likely will not understand what they just read.

Try to state the key idea in the first sentence of the paragraph, then expand on it in more detail and back it up with examples. That way the reader can skim the text diagonally and immediately see what each part is about. Sometimes the first sentences of a paragraph are set in bold — these are called run-in headings.

A paragraph should convey and develop only one idea. For example, if you mix the causes, the essence of the problem, and possible solutions to the situation you are describing in a single paragraph, the reader will quickly get tired and most likely will not understand what they just read.

Try to state the key idea in the first sentence of the paragraph, then expand on it in more detail and back it up with examples. That way the reader can skim the text diagonally and immediately see what each part is about. Sometimes the first sentences of a paragraph are set in bold — these are called run-in headings.

  • Статичные алерты. Хост применяет только CSS-классы и не задаёт ARIA-роль — это правильно для алерта, отрисованного вместе со страницей: принудительный role="alert" заставил бы скринридер неожиданно зачитать содержимое при загрузке страницы.
  • Динамически показываемые алерты. Когда алерт появляется в ответ на действие пользователя (ошибка валидации, изменение статуса), добавьте role="alert" для срочных сообщений или aria-live="polite" с aria-atomic="true" для несрочного статуса, чтобы вспомогательные технологии его озвучили. Как вариант — объявляйте сообщение через LiveAnnouncer из @angular/cdk/a11y.
  • Статус только цветом иконки. Статус передаётся цветом иконки, который воспринимается не всеми пользователями. Повторяйте статус в заголовке или тексте (либо добавляйте визуально скрытый текст, например <span class="cdk-visually-hidden">Ошибка:</span>), а декоративную иконку статуса помечайте aria-hidden="true".
  • Кнопка закрытия. Размещайте кнопку закрытия на нативном <button> с доступным именем (aria-label="Закрыть"), чтобы она была доступна и управлялась с клавиатуры.
  • Фокус при закрытии. Закрытие алерта, когда фокус находится на его кнопке закрытия, сбрасывает фокус на <body>. Переведите фокус на логичный элемент после удаления — предпочтительно через FocusMonitor.focusVia из @angular/cdk/a11y, чтобы сохранить кольцо фокуса.
Предложения по улучшению
Если вы нашли ошибку или хотите доработать статью, создайте запрос на GitHub.