Angular UI/Material Design Flashcards

1
Q

Angular Flex-Layout

A

https://www.npmjs.com/package/@angular/flex-layout

Angular Flex Layout provides a sophisticated layout API using Flexbox CSS + mediaQuery. This module provides Angular developers with component layout features using a custom Layout API, mediaQuery observables, and injected DOM flexbox-2016 CSS stylings.

The Flex Layout engine intelligently automates the process of applying appropriate Flexbox CSS to browser view hierarchies. This automation also addresses many of the complexities and workarounds encountered with the traditional, manual, CSS-only application of box CSS.

The real power of Flex Layout, however, is its responsive engine. The Responsive API enables developers to easily specify different layouts, sizing, visibilities for different viewport sizes and display devices.

Getting Started
Start by installing the Angular Layout library from npm

npm i -s @angular/flex-layout @angular/cdk

Next, you’ll need to import the Layout module in your app’s module.

app.module.ts

import { FlexLayoutModule } from ‘@angular/flex-layout’;

@NgModule({
    ...
    imports: [ FlexLayoutModule ],
    ...
});
After that is configured, you can use the Angular Layout attributes in your HTML tags for flex layout:

<div>
</div>

https://github.com/angular/flex-layout

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Angular Flex-Layout static API Overview

A

The Angular Layout features provide smart, syntactic directives to allow developers to easily and intuitively create responsive and adaptive layouts using Flexbox and CSS Grid.

The API outline here is considered static and provides a UX that will adjust element sizes and positions as the browser window width changes. The static API can be considered the default desktop layout API.

Developers should use the Responsive API to support alternate layout configurations for mobile or tablet devices

The Angular Layout API is an intuitive list of HTML directives (aka attributes) that can be used on HTML containers and elements. Instead of using traditional CSS stylesheets, developers will define their layouts declaratively directly in the HTML.

An important, fundamental concept is understanding which APIs are used on DOM containers versus APIs used on DOM child elements in those containers.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

angular flex layout static api for DOM container

A

HTML API Allowed values
fxLayout [wrap] row | column | row-reverse | column-reverse
fxLayoutAlign main-axis: start | center | end | space-around | space-between | space-evenly; cross-axis: start | center | end | stretch | space-between | space-around | baseline
fxLayoutGap % | px | vw | vh
gdAlignColumns main-axis: start | center | end | space-around | space-between | space-evenly | stretch; cross-axis: start | center | end | stretch
gdAlignRows main-axis: start | center | end | space-around | space-between | space-evenly | stretch; cross-axis: start | center | end | stretch
gdAreas names separated by |, e.g. gdAreas=”area1 | area2 | area3” gdInline for inline-grid
gdAuto row | column | dense | row dense | column dense gdInline for inline-grid
gdColumns any valid input for grid-template-columns gdInline for inline-grid
! at the end means grid-auto-columns
gdRows any valid input grid-template-rows gdInline for inline-grid
! at the end means grid-auto-rows
gdGap % | px | vw | vh gdInline for inline-grid
These directives affect the flow and layout children elements in the container

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

angular flex layout static api for DOM elements

A
API for DOM elements:
HTML	Allowed values
fxFlex	"" | px | % | vw | vh |   ,
fxFlexOrder	int
fxFlexOffset	% | px | vw | vh
fxFlexAlign	start | baseline | center | end
fxFlexFill, fxFill	
gdArea	string name for the area as defined in gdAreas
gdColumn	any valid value for grid-column
gdRow	any valid value for grid-row
gdGridAlign	 
These directives affect the layout and size of the host element. Note the API expects their host elements to be inside a DOM container (a 'block' element which is itself using the Layout API for containers).
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

angular flex layout static api for any element

A
API for any element:
HTML API	Allowed values
fxHide	TRUE | FALSE | 0 | ""
fxShow	TRUE | FALSE | 0 | ""
ngClass	@extends ngClass core
ngStyle	@extends ngStyle core
imgSrc	@extends  src attribute
Shown below is sample HTML markup that uses both the container and element Static API:

<div>

<div></div>
<div>

<div></div>
<div></div>
<div></div>

</div>
<div></div>

</div>

Angular Layout directives assign CSS styles directly in-line to the host element. These in-line styles override inherited styles, ShadowDOM styles and even ShadowDOM tree stylings on the element :host

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Prgrammatic usage for angular flex layout

A

Most of the Angular Layout functionality is provided via Directives used declaratively in template HTML. There are two (2) programmatic features, however, that are published for programmatic usages:

MediaObserver:
Injectable service used to subscribe to MediaQuery activation changes. You can access its observable through the media$ property
import {MediaObserver} from ‘@angular/flex-layout’;
constructor(public mediaObserver: MediaObserver ) {
mediaObserver.media$.subscribe(…);
}
BREAKPOINT:
Injection token used to override or extend the default breakpoints with custom MediaQuery breakpoints.
import {BREAKPOINT} from ‘@angular/flex-layout’;
providers: [{provide: BREAKPOINT, useValue: MY_CUSTOM_BREAKPOINTS, multi: true}]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Special Responsive Features

A

Special Responsive Features
While the following APIs also add or remove DOM element inline styles, they are NOT FlexBox CSS specific.

Instead these are Responsive APIs used to adjust specific, non-flexbox styles when a specific mediaQuery has activated:

fxShow: This markup specifies if its host element should be displayed (or not)

<div></div>

fxHide: This markup specifies if its host element should NOT be displayed

<div></div>

ngClass : Enhances the ngClass directives with class changes based on mediaQuery activations

<div></div>

ngStyle: Enhances the ngStyle directive with style updates based on mediaQuery activations

<div></div>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Static API:

A
HTML API (Declarative)
The features of Angular Layout are best used declaratively in template HTML. This API has two (2) significant feature sets:

Static API: Summary of static API features.
Responsive API: Introducing Responsive API and BreakPoints details.
As each directive (aka API) within the library has its own constraints and options, the links below should be used to navigate to the specific documentation pages for each directive

Containers
This API set applies CSS stylings for DOM container elements with 1 or more nested children:

fxLayout: Defines the flow order of child items within a flexbox container

<div></div>

fxLayoutGap: Defines if child items within a flexbox container should have a gap

<div></div>

fxLayoutAlign: Defines how flexbox items are aligned according to both the main-axis and the cross-axis, within a flexbox container

<div></div>

gdAlignColumns: Aligns the items column-wise

<div></div>

gdAlignRows: Aligns the items row-wise

<div></div>

gdAreas: Describes the areas the grid contains

<div></div>

gdAuto: Controls the auto placement for the grid

<div></div>

gdColumns: Defines the line names and track sizing functions of the grid columns

<div></div>

gdRows: Defines the line names and track sizing functions of the grid rows

<div></div>

gdGap: Defines the gap between grid items

<div></div>

Child Elements within Containers
This API set applies CSS stylings for a DOM element nested within a DOM container:

fxFlex: This markup specifies the resizing of its host element within a flexbox container flow

<div></div>

fxFlexOrder: Defines the order of a flexbox item

<div></div>

fxFlexOffset: Offset a flexbox item in its parent container flow layout

<div></div>

fxFlexAlign: Works like fxLayoutAlign, but applies only to a single flexbox item, instead of all of them

<div></div>

fxFlexFill:
Maximizes width and height of element in a layout container

<div></div>

gdArea: Marks the element as a CSS Grid area

<div></div>

gdColumn: Specifies a grid item’s size and location within the grid column

<div></div>

gdRow: Specifies a grid item’s size and location within the grid row

<div></div>

gdGridAlign: Aligns a grid item within its container element

<div></div>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Responsive API

A

Responsive layouts in Material Design adapt to any possible screen size. Google’s specifications provide guidance that includes a flexible grid that ensures consistency across layouts, breakpoint details about how content reflows on different screens, and a description of how an app can scale from small to extra-large screens.

Enhancing the Static API
Developers should consult the HTML Declarative API for specific Static API details, then simply extend the HTML markup usages by adding the responsive suffixes (as discussed below)!

Angular Layout will automatically handle all the details around listening for mediaQuery activations and applying the responsive values to the host DOM elements.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Responsive Features

A

Responsive Features
To extend the static API with responsive features, we will first associate specific breakpoint aliases with mediaQuery values.

MediaQueries and Aliases
We can associate breakpoints with mediaQuery definitions using breakpoint alias(es):

breakpoint mediaQuery
xs ‘screen and (max-width: 599px)’
sm ‘screen and (min-width: 600px) and (max-width: 959px)’
md ‘screen and (min-width: 960px) and (max-width: 1279px)’
lg ‘screen and (min-width: 1280px) and (max-width: 1919px)’
xl ‘screen and (min-width: 1920px) and (max-width: 5000px)’
lt-sm ‘screen and (max-width: 599px)’
lt-md ‘screen and (max-width: 959px)’
lt-lg ‘screen and (max-width: 1279px)’
lt-xl ‘screen and (max-width: 1919px)’
gt-xs ‘screen and (min-width: 600px)’
gt-sm ‘screen and (min-width: 960px)’
gt-md ‘screen and (min-width: 1280px)’
gt-lg ‘screen and (min-width: 1920px)’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Example of applying responsive api on static api for flex layout

A

If we combine the breakpoint alias with the static API, we can easily support responsive breakpoints using a simple markup convention:

The alias is used as suffix extensions to the static API HTML markup:

.=””
[.]=””
Below is an example usage of the Responsive Layout API:

<div>

<div></div>
<div>

<div></div>
<div></div>
<div></div>

</div>
<div></div>

</div>

In the markup above the HTML API directives use both static values and expression bindings; where the values are expressed as raw, percentage, or pixel values.

Note: numeric values not explicitly annotated as px, vw, or vh default to percentage values.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Breakpoint Activation Fallback Algorithm –Not Clear

A

When a breakpoint is activated and the hosting element does NOT have a responsive API defined for the newly activated breakpoint, the Flex-Layout responsive engine uses a fallback, descending-scan algorithm to determine the replacement activation value. The algorithm uses breakpoint priorities to sort activate breakpoints by descending-priority.

This algorithm searches:

For non-overlapping breakpoints: the search scans from smallest-to-largest breakpoint range to find the closest, matching activation value.
(xs, sm, md, lg, xl)
For overlapping breakpoints: the search scans from smallest-to-largest breakpoint range to find the closest, matching activation value.
(lt-sm, lt-md, lt-lg, lt-xl); where lt-xl is the largest range
(gt-xs, gt-sm, gt-md, gt-lg); where gt-xs is the largest range.
Developers should consider (highest priority to lowest priority) equates to (smallest range to largest range).

Consider the following responsive markup examples:

Example #1

<div> ... </div>

When the activated breakpoint is:

xl, then fallback to the default fxShow; so the div is shown
lg, then the div is hidden (since the value === ‘true’)
md, then fallback to the default fxShow; so the div is shown
sm, then fallback to the default fxShow; so the div is shown
xs, then the div is shown (since the value === ‘false’)
Example #2

<div> ... </div>

When the activated breakpoint is:

xl, then fallback to ‘gt-sm’ so the div sizing is 100%
lg, then fallback to ‘gt-sm’ so the div sizing is 100%
md, then fallback to ‘gt-sm’ so the div sizing is 100%
sm, then fallback to the default fxFlex=”50%”; so the div sizing is 50%
xs, then fallback to the default fxFlex=”50%”; so the div sizing is 50%
Example #3
screen shot 2019-01-01 at 7 00 56 pm

https://github.com/angular/flex-layout/wiki/Responsive-API

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

CSS Flex Layout links

A

https: //github.com/angular/flex-layout
https: //github.com/angular/flex-layout/wiki/Declarative-API-Overview
https: //github.com/angular/flex-layout/wiki/API-Documentation
https: //github.com/angular/flex-layout/wiki/Responsive-API
https: //tburleson-layouts-demos.firebaseapp.com/#/docs

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

API for DOM containers-fxLayout API

A

https://github.com/angular/flex-layout/wiki/fxLayout-API

The fxLayout directive should be used on DOM containers whose children should layout or flow as the text direction along the main-axis or the cross-axis.

<div>
<div>1. One</div> <div>2. Two</div> <div>3. Three</div> <div>4. Four</div>
</div>

or

<div>
  <div>1. One</div>
  <div>2. Two</div>
  <div>3. Three</div>
  <div>4. Four</div>
</div>

fxLayout Options
Shown below are the supported fxLayout directive values and their resulting CSS stylings on the hosting element container:

Value	Equivalent CSS
'' (default)	flex-direction: row
row	flex-direction: row
row-reverse	flex-direction: row-reverse
column	flex-direction: column
column-reverse	flex-direction: column-reverse

fxLayout Side-Effects
Changes to the fxLayout value will cause the following directives to update and modify their element stylings:

fxLayoutGap
fxFlex
fxLayoutAlign

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

API for DOM containers-fxLayout + wrap

A

fxLayout + wrap
By default, flex items will not wrap in their container. Formerly published as distinct directive, fxLayoutWrap was deprecated in favor of simply adding the wrap parameter as a secondary option to the fxLayout directive.

<div>
<div>1. One</div> <div>2. Two</div> <div>3. Three</div> <div>4. Four</div>
</div>

Note: when using wrap, developers must first specify the layout direction.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

API for DOM containers-fxLayout + inline

A

fxLayout + inline
There are some instances where developers want to use the inline-flex CSS display property, instead of the default. Angular Layout provides this option by accepting a secondary argument to the fxLayout directive as follows:

<div>
<div>1. One</div> <div>2. Two</div> <div>3. Three</div> <div>4. Four</div>
</div>

Note: when using inline, developers must first specify the layout direction.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

API for DOM containers-fxLayoutAlign API

A

The fxLayoutAlign directive should be used on DOM containers whose children should be aligned on the main and cross-axis (optional)

<div>
<div>1. One</div> <div>2. Two</div> <div>3. Three</div> <div>4. Four</div>
</div>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

API for DOM containers-fxLayoutAlign API - Main-axis

A

horizantal axis like justify-content:center

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

API for DOM containers-fxLayoutAlign API - Cross -axis

A

vertical alignement :align-items: center; align-content: center

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

API for DOM containers-fxLayoutAlign Options

A

Shown below are the supported fxLayoutAlign directive values and their resulting CSS stylings on the hosting element container

<div>
<div>1. One</div> <div>2. Two</div> <div>3. Three</div> <div>4. Four</div>
</div>

Main Axis

Value Equivalent CSS
(default) justify-content: flex-start
start or flex-start justify-content: flex-start
center justify-content: center
end or flex-end justify-content: flex-end
space-around justify-content: space-around
space-between justify-content: space-between
space-evenly justify-content: space-evenly
Cross Axis (optional)

Value Equivalent CSS
(default) align-items: stretch; align-content: stretch
start or flex-start align-items: flex-start; align-content: flex-start
center align-items: center; align-content: center
end or flex-end align-items: flex-end; align-content: flex-end
space-around align-items: space-around; align-content: space-around
space-between align-items: space-between; align-content: space-between
stretch max-width: 100% if flex-direction: column; else max-height: 100%
baseline align-items: baseline; align-content: stretch

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

API for DOM containers-fxLayoutGap API

A

The fxLayoutGap directive should be used on to specify margin gaps on children within a flexbox container (e.g. nested within a fxLayout container). There is a secondary mode to enable a gutter system with a margin applied on the host element.

Default Mode
margin-right used when the parent container flex-direction == “row”
margin-bottom used when the parent container flex-direction == “column”
Note that the last child item will NOT have a margin gap specified; only the inside gaps are specified. Additionally, fxLayoutGap does not respond to reveresed flow directions: column-reverse or row-reverse are used.

Examples:
Flex-Direction: Row
<div>
  <div>1. One</div> <div>2. Two</div> <div>3. Three</div> <div>4. Four</div>
</div>
lg_1
<div>
  <div>1. One</div> <div>2. Two</div> <div>3. Three</div> <div>4. Four</div>
</div>
----
Flex-Direction: Column
<div>
  <div>1. One</div> <div>2. Two</div> <div>3. Three</div> <div>4. Four</div>
</div>
fxLayout_column

<div>
<div>1. One</div> <div>2. Two</div> <div>3. Three</div> <div>4. Four</div>
</div>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

API for DOM containers-Using fxLayoutGap with Wrap

A

When using wrap with fxLayout to wrap rows or columns, developers should account for the gap sizes when specifying the child item sizes (using fxFlex).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

API for DOM containers-Grid Mode - not clear

A

To use fxLayoutGap with a gutter system, simply append the suffix grid to any fxLayoutGap value. For instance:

<div>
  <div>Section 1</div>
  <div>Section 2</div>
  <div>Section 3</div>
</div>
This creates a gutter system by applying a margin to the host element and an inverse padding to each child. Other than this change, it works exactly as the default mode. It also takes flex-order and hidden elements into account, and has the same responsive abilities as the default mode.

Please note that unlike the standard gap functionality, fxLayoutGap with the grid keyword applies a padding to each child element to add the gutter, in addition to the margin on the host element.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

API for DOM elements: -

A
HTML	Allowed values
fxFlex	"" | px | % | vw | vh |   ,
fxFlexOrder	int
fxFlexOffset	% | px | vw | vh
fxFlexAlign	start | baseline | center | end
fxFlexFill, fxFill	
gdArea	string name for the area as defined in gdAreas
gdColumn	any valid value for grid-column
gdRow	any valid value for grid-row
gdGridAlign
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

API for DOM containers:

A

HTML API Allowed values
fxLayout [wrap] row | column | row-reverse | column-reverse
fxLayoutAlign main-axis: start | center | end | space-around | space-between | space-evenly; cross-axis: start | center | end | stretch | space-between | space-around | baseline
fxLayoutGap % | px | vw | vh
gdAlignColumns main-axis: start | center | end | space-around | space-between | space-evenly | stretch; cross-axis: start | center | end | stretch
gdAlignRows main-axis: start | center | end | space-around | space-between | space-evenly | stretch; cross-axis: start | center | end | stretch
gdAreas names separated by |, e.g. gdAreas=”area1 | area2 | area3” gdInline for inline-grid
gdAuto row | column | dense | row dense | column dense gdInline for inline-grid
gdColumns any valid input for grid-template-columns gdInline for inline-grid
! at the end means grid-auto-columns
gdRows any valid input grid-template-rows gdInline for inline-grid
! at the end means grid-auto-rows
gdGap % | px | vw | vh gdInline for inline-grid

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

API for any element:

A
HTML API	Allowed values
fxHide	TRUE | FALSE | 0 | ""
fxShow	TRUE | FALSE | 0 | ""
ngClass	@extends ngClass core
ngStyle	@extends ngStyle core
imgSrc	@extends  src attribute
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

API for DOM elements:fxFlex API

A

https://github.com/angular/flex-layout/wiki/fxFlex-API
The fxFlex directive should be used on elements within a fxLayout container and identifies the resizing of that element within the flexbox container flow.

This directive is the smartest, most powerful directive within the flex-layout API toolbox and is essentially the FlexBox API for resizing elements in horizontal or vertical stacks.

Flexbox element resizing utilizes three (3) parameters:

flex-grow: defines how much a flexbox item should grow (proportional to the others) if there’s space available. The flex-grow value overrides the width.
flex-shrink: defines how much a flexbox item should shrink if there is not enough space available.
flex-basis: controls the default size of an element, before it is manipulated by other Flexbox properties
Note that the resizing occurs along the main-axis of the layout and maybe affected by the fxLayoutAlign options.

<div>
<div></div></div>

means

Resize the div element to fill the available space along the
horizontal, main-axis flow of its parent container!
The notation:

<div>
   <div></div>
   <div></div>
   <div></div></div>
means

Resize the div elements to fill 1/3rd each the available space
along horizontal main-axis.

<div>

<div>
<div>This is a blurb.</div>
<div>This is a blurb.</div>
<div>This is a blurb.</div>
</div>

</div>

https://stackblitz.com/edit/flex-layout-angular-material-csc4zz?file=app%2Fapp.component.html

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

API for DOM elements: fxFlex Attribute Usages

A

The fxFlex directive supports two usages: short-form and long-form:

<div></div>

or

<div></div>

The long-form enables the developer to specify the grow, shrink, and basis values inline.

fxFlex=”1 1 52%”
fxFlex=”3 3 calc(15em + 20px)”
fxFlex=”1 1 auto”
The short-form enables developers to specify only the flex-basis and uses defaults for the shrink and grow options: (default values == 1).

fxFlex
fxFlex=""
fxFlex="2 2 calc(10em + 10px)"
fxFlex="102px"
Note the above examples are using static values. To use runtime expressions, developers should use the box-notation to specify 1-way DataBind (to an expression). E.g. [fxFlex]="twoColumnSpan"

fxFlex Options
The flex-basis values can be pixels, percentages, calcs, em, vw, vh, or known aliases

fxFlex
fxFlex=""
fxFlex="2 2 calc(10em + 10px)"
fxFlex="102px"
fxFlex="auto"
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

API for DOM elements: Flex-basis aliases

A

Flex-basis aliases are accepted shorthand terms used to quickly specify Flexbox stylings. Here are the industry mappings of the alias to its resulting CSS styling:

alias	Equivalent CSS
grow	flex: 1 1 100%
initial	flex: 0 1 auto
auto	flex:   100%
none	flex: 0 0 auto
nogrow	flex: 0 1 auto
noshrink	flex: 1 0 auto
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

API for DOM elements:fxFlex

A

fxFlex also auto-assign additional stylings, dependent upon the fxFlex value used and the layout, main-axis direction:

box-sizing : border-box
When a parent fxLayout container changes flow-direction, the fxFlex directive will automatically update the element’s inline-styling with corrected stylings.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

API for DOM elements:Default fxFlex Values

A

When the Angular compiler builds an instance of the FlexDirective, it initializes the

import {Input} from ‘@angular/core’;
@Input(‘fxFlex’)
set(val) {….}
with the static value of “”. fxFlex is the same/equivalent as fxFlex=””. And this empty string value is internally interpreted (by the FlexDirective) as an instruction to assign an inline element-styling of

flex: 1 1 0.000000001px
Where the default values of flew-shrink and flex-grow are 1 and have not been overridden.

Another usage (with distinct grow and shrink values) such as

<div></div>

would result in an inline styling of

flex: 2 0 0.000000001px
What this means to the developer is an intuitive resizing for elements:

The notation

<div>
<div><div>
</div>
means

Resize the div element to fill the available space along the
horizontal, main-axis flow of its parent container!
The notation:

~~~
<div>
<div><div>
<div><div>
<div><div>
</div>
means
~~~

Resize the div elements to fill 1/3rd each the available space
along horizontal main-axis. </div></div></div></div></div></div></div></div>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

API for DOM elements:fxFlexOrder API

A

The fxFlexOrder directive should be used on elements within a sorted fxLayout container and identifies the positional ordering of the element

<div>
  <div>1. One</div>
  <div>2. Two</div>
  <div>3. Three</div>
  <div>4. Four</div>
</div>
fxFlexOrder Options
fxFlexOrder takes a single integer as argument, and populates its host element with the following inline CSS styling

Value Equivalent CSS
(default) order: 0
order:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

API for DOM elements:fxFlexOffset

A

The fxFlexOffset directive should be used on on elements within a fxLayout container and dictates the margin between elements (RTL support coming soon!)

<div>
  <div>1. One</div>
  <div>2. Two</div>
  <div>3. Three</div>
  <div>4. Four</div>
</div>
fxFlexOffset Options
fxFlexOffset takes a single parameter as argument, and populates its host element with the following inline CSS styling

Note: fxFlexOffset supports the following suffixes: % (default) | px | vw | vh

Value Equivalent CSS
(default) margin-left: 0%
margin-left:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

API for DOM elements:fxFlexAlign API

A

The fxFlexAlign directive should be used on on elements within a sorted fxLayout container and dictates how the element should be aligned, overriding the container cross-axis alignment setting

<div>
  <div>1. One</div>
  <div>2. Two</div>
  <div>3. Three</div>
  <div>4. Four</div>
</div>
fxFlexAlign Options
Shown below are the supported fxFlexAlign directive values and their resulting CSS stylings on the hosting element container
Value	Equivalent CSS
start	align-self: flex-start
center	align-self: center
end	align-self: flex-end
baseline	align-self: baseline
stretch	align-self: stretch
Note: All supported values for align-self are supported by this directive
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

API for DOM elements:fxFlexFill API

A

The fxFlexFill directive should be used on elements within a fxLayout container and identifies the element whose width and height should be maximized

<div>
<div>1. One</div> <div>2. Two</div> <div>3. Three</div> <div>4. Four</div>
</div>

fxFlexFill Options
fxFlexFill takes no arguments, and populates its host element with the following inline CSS styling:

Key	Value
margin	0
width	100%
height	100%
min-width	100%
min-height
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

API for DOM elements Note

A

These directives affect the layout and size of the host element. Note the API expects their host elements to be inside a DOM container (a ‘block’ element which is itself using the Layout API for containers).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

API for any element: fxHide

A

API for any element: fxHide
The fxHide directive allows developers to dynamically and/or responsively show/hide the hosting element. The fxHide logic defaults to hiding an element.

API
Flex-Layout supports STATIC API for responsive layouts using the API without . alias suffixes: fxShow, fxHide, etc. These values of these directives are used (and styles applied) regardless of the viewport size. These static rules can be specifically overridden by a registered responsive API use (see below).

Flex-Layout provides a RESPONSIVE API for dynamic adaptive layouts. This is simply using the the static API with mediaQuery alias suffixes. e.g.

fxHide.lg, etc.
fxShow.gt-sm,
Using fxShow & fxHide
fxHide (without a value) means “display:none”
fxShow (without a value) means use the origin display style value
fxHide=”false” means use the original display value (should no longer be hidden)
fxShow=”false” means “display:none” and hide it.
fxHide is the inverse of fxShow

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

using Responsive api for hiding

A

Using Responsive API
When a mediaQuery range activates, the directive instances will be notified. If the current activate mediaQuery range (and its associated alias) are not used, then the static API value is restored as the fallback value.

The fallback solution uses a largest_range-to-smallest_range search algorithm. Consider the following:

<div></div>

When the lg range is activated (by viewport resizing,etc) the div is hidden since the gt-md is used as the closest descending fallback value.
When the md range is activated, the div is shown since the static API is the closest descending matching condition.
When the sm range is activated the div is hidden.
Please note that there is no left-to-right precedence. This is an incorrect interpretation..

Combine Uses of fxShow + fxHide
We can leverage the default values of these directives select specific conditions when an element is hidden or shown.

Consider:

<div></div>

means the the above element will be hidden by default and ONLY shown on viewport sizes greater than mobile.

<div></div>

means the the above element will be shown by default and ONLY hidden on viewport sizes == md mediaQuery ranges.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

API for any element:fxShow API

A

The fxShow directive allows developers to dynamically and/or responsively show/hide the hosting element. The fxShow logic defaults to showing an element.

API
Flex-Layout supports STATIC API for responsive layouts using the API without . alias suffixes: fxShow, fxHide, etc. These values of these directives are used (and styles applied) regardless of the viewport size. These static rules can be specifically overridden by a registered responsive API use (see below).

Flex-Layout provides a RESPONSIVE API for dynamic adaptive layouts. This is simply using the the static API with mediaQuery alias suffixes. e.g.

fxShow.gt-sm,
fxHide.lg, etc.
Using fxShow & fxHide
fxShow (without a value) means use the origin display style value
fxHide (without a value) means “display:none”
fxShow=”false” means “display:none” and hide it.
fxHide=”false” means use the original display value (should no longer be hidden)
fxHide is the inverse of fxShow

Using Responsive API
When a mediaQuery range activates, the directive instances will be notified. If the current activate mediaQuery range (and its associated alias) are not used, then the static API value is restored as the fallback value.

The fallback solution uses a largest_range-to-smallest_range search algorithm. Consider the following:

<div></div>

When the lg range is activated (by viewport resizing,etc) the div is hidden since the gt-md is used as the closest descending fallback value.
When the md range is activated, the div is shown since the static API is the closest descending matching condition.
When the sm range is activated the div is hidden.
Please note that there is no left-to-right precedence. This is an incorrect interpretation..

Overlapping Responsive API Usages
When multiple overlapping breakpoint aliases are used, the one with the largest range wins.

Consider:

<div></div>

When the media range for md activates, then both gt-md and gt-xs responsive usages ^ will match. But gt-xs matches last so that value will be used and therefore the div element will be shown.

Combine Uses of fxShow + fxHide
We can leverage the default values of these directives select specific conditions when an element is hidden or shown.

Consider:

<div></div>

means the the above element will be hidden by default and ONLY shown on viewport sizes greater than mobile.

<div></div>

means the the above element will be shown by default and ONLY hidden on viewport sizes == md mediaQuery ranges.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

ngClass API - flex

A

The @angular/flex-layout ngClass directive is a subclass of the @angular/common ngClass directive.

Standard class Features
Note that the default classes (specified by class="" and ngClass="..." will be preserved (and merged) into other activation class lists UNLESS the breakpoint has specified that a default class should be removed.

For example:

<div></div>

By default the div will have only the class0 classname assigned.

When the xs breakpoint activates, then the div will have class0 class1 class2 assigned.
When the xs breakpoint deactivates, then the div will only have the class0 name assigned.
Standard ngClass Features
Traditionally ngClass adds and removes CSS classes on an HTML element:

The CSS classes are updated as follows, depending on the type of the expression evaluation:

string - the CSS classes listed in the string (space delimited) are added,
Array - the CSS classes declared as Array elements are added,
Object - keys are CSS classes that get added when the expression given in the value evaluates to a truthy value, otherwise they are removed.

Responsive Features
The Flex-Layout ngClass adds responsive features to also add/remove CSS classes; but only for activated breakpoints.

ngClass. ; where alias == xs | sm | md | etc.
Example #1:
<div>
      TESTING
</div>
class

See Plunkr Demo

Example #2:
<div>
     TESTING
</div>
class2

See Plunkr Demo

Merging Classes
Note that the default classes (specified by class="" and ngClass="..." will be preserved (and merged) into other activation class lists UNLESS the breakpoint has specified that a default class should be removed:

Below the class first is used for all mediaQuery activations except for ‘xs’ (mobile) where it is explicitly removed;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

ngStyle api

A

The @angular/flex-layout ngStyle directive is a subclass of the @angular/common ngStyle directive.

ngStyle Enhancements
Supports merging style key-values into non-responsive [ngStyle] options
Supports responsive [ngStyle.] usages; see section below
Standard (non-responsive) Features
Traditionally ngStyle updates an HTML element inline styles (highest specificity):

The styles are updated according to the value of the expression evaluation:

keys are style names with an optional . suffix (ie ‘top.px’, ‘font-style.em’),
values are the values assigned to those properties (expressed in the given unit).

Note: using ngStyle with style will cause the initial style key/values to be merged into the ngStyle options.

Responsive Features
The Flex-Layout ngClass adds responsive features to also add/remove CSS styles for activated breakpoints.

screen shot 2017-09-15 at 6 04 16 pm

See Plunkr Demo

Merging Styles
Note that the default styles (specified by style="" or ngStyle="...") will be preserved (and merged) into other activation class lists UNLESS the breakpoint has specified that a style should be removed (using a null value)

Below the font size and colors are changed for ‘sm’ and ‘md’ breakpoints. Yet for ‘md’, the text-align style remains the same as the default === ‘left’. Deactivations of ‘sm’ or ‘md’ breakpoints to other breakpoints will result in only the default styles being re-applied.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

imgSrc API

A

The imgSrc directive is a responsive extension of the HTML src attribute and can be used on any tag in the markup

<div>
  <img>
</div>
imgSrc Options
imgSrc takes one string argument, and alters its host's src attribute as necessary when breakpoints are activated. The initial value will be used as the default and fallback when a responsive alias is not defined
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q

sample HTML markup that uses both the container and element Static API

A

Shown below is sample HTML markup that uses both the container and element Static API:

<div>

<div></div>
<div>

<div></div>
<div></div>
<div></div>

</div>
<div></div>

</div>

Angular Layout directives assign CSS styles directly in-line to the host element. These in-line styles override inherited styles, ShadowDOM styles and even ShadowDOM tree stylings on the element :host

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

mat-expansion-panel

A

https://material.angular.io/components/expansion/overview

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
45
Q

mat-accordion

A

Multiple expansion-panels can be combined into an accordion. The multi=”true” input allows the expansions state to be set independently of each other. When multi=”false” (default) just one panel can be expanded at a given time:
https://material.angular.io/components/expansion/overview

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
46
Q

mat-table

A
  1. Write your mat-table and provide data
    Begin by adding the component to your template and passing in data.

The simplest way to provide data to the table is by passing a data array to the table’s dataSource input. The table will take the array and render a row for each object in the data array.

Since the table optimizes for performance, it will not automatically check for changes to the data array. Instead, when objects are added, removed, or moved on the data array, you can trigger an update to the table’s rendered rows by calling its renderRows() method.

While an array is the simplest way to bind data into the data source, it is also the most limited. For more complex applications, using a DataSource instance is recommended. See the section “Advanced data sources” below for more information.

  1. Define the column templates
    Next, write your table’s column templates.

Each column definition should be given a unique name and contain the content for its header and row cells.

Here’s a simple column definition with the name ‘score’. The header cell contains the text “Score” and each row cell will render the score property of each row’s data.

Score
{{user.score}}

Note that the cell templates are not restricted to only showing simple string values, but are flexible and allow you to provide any template.

If your column is only responsible for rendering a single string value for the header and cells, you can instead define your column using the mat-text-column. The following column definition is equivalent to the one above.

Check out the API docs and examples of the mat-text-column to see how you can customize the header text, text alignment, and cell data accessor. Note that this is not compatible with the flex-layout table. Also, a data accessor should be provided if your data may have its properties minified since the string name will no longer match after minification.

  1. Define the row templates
    Finally, once you have defined your columns, you need to tell the table which columns will be rendered in the header and data rows.

To start, create a variable in your component that contains the list of the columns you want to render.

columnsToDisplay = [‘userName’, ‘age’];
Then add mat-header-row and mat-row to the content of your mat-table and provide your column list as inputs.

Note that this list of columns provided to the rows can be in any order, not necessarily the order in which you wrote the column definitions. Also, you do not necessarily have to include every column that was defined in your template.

This means that by changing your column list provided to the rows, you can easily re-order and include/exclude columns dynamically.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
47
Q

tha mat-table column defination

A

the column definitions should match the columnstoDisplay array ; in we array we could specify which ever columns we want to display and the order

export class StaffComponent implements OnInit {
displayedColumns: string[] = [‘id’, ‘firstName’, ‘lastName’, ‘email’, ‘phone1’, ‘positionId’, ‘credentialId’, ‘isRegistry’, ‘responsibilities’];
staff: Staff[];
dataSourceStaff: MatTableDataSource;
constructor(private rest: RestService) {
this.dataSourceStaff = new MatTableDataSource;
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
48
Q
A

provides an expandable details-summary view.

Expansion-panel content
Each expansion-panel must include a header and may optionally include an action bar.

Header
The shows a summary of the panel content and acts as the control for expanding and collapsing. This header may optionally contain an and an , which format the content of the header to align with Material Design specifications.

By default, the expansion-panel header includes a toggle icon at the end of the header to indicate the expansion state. This icon can be hidden via the hideToggle property.

  This is the expansion title

  This is a summary of the content

<p>This is the primary content of the panel.</p>

Action bar
Actions may optionally be included at the bottom of the panel, visible only when the expansion is in its expanded state.

This is the expansion title

<p>This is the primary content of the panel.</p>

Click me

Disabling a panel
Expansion panels can be disabled using the disabled attribute. A disabled expansion panel can’t be toggled by the user, but can still be manipulated programmatically.

This is the expansion title

This is a summary of the content
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
49
Q
A

Accordion
Multiple expansion-panels can be combined into an accordion. The multi=”true” input allows the expansions state to be set independently of each other. When multi=”false” (default) just one panel can be expanded at a given time:

  This is the expansion 1 title

This the expansion 1 content

  This is the expansion 2 title

This the expansion 2 content
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
50
Q
  • Lazy rendering
A

By default, the expansion panel content will be initialized even when the panel is closed. To instead defer initialization until the panel is open, the content should be provided as an ng-template:

This is the expansion title

Some deferred content
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
51
Q

-Accessibility

A

The expansion-panel aims to mimic the experience of the native and elements. The expansion panel header has role=”button” and also the attribute aria-controls with the expansion panel’s id as value.

The expansion panel headers are buttons. Users can use the keyboard to activate the expansion panel header to switch between expanded state and collapsed state. Because the header acts as a button, additional interactive elements should not be put inside of the header.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
52
Q

table like mat-accordion

A

<span>Name</span>
<span>Vessel Id</span>
<span>Status</span>
<span>IRCS</span>

  <span class="mat-cell">{{item.vesselName}}</span>
  <span class="mat-cell">{{item.vesselId}}</span>
  <span class="mat-cell">{{item.vesselStatus}}</span>
  <span class="mat-cell">{{item.ircs}}</span>

<div><pre>{{item | json}}</pre></div>
---
styles:
.mat-table
{
    display:block;
}
.mat-cell, .mat-header-cell {
    flex: 1;
    overflow: hidden;
    word-wrap: break-word;
  }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
53
Q

CdkTable

A

https://material.angular.io/cdk/table/overview
The CdkTable is an unopinionated, customizable data-table with a fully-templated API, dynamic columns, and an accessible DOM structure. This component acts as the core upon which anyone can build their own tailored data-table experience.

The table provides a foundation upon which other features, such as sorting and pagination, can be built. Because it enforces no opinions on these matters, developers have full control over the interaction patterns associated with the table.
For a Material Design styled table, see the documentation for MatTable which builds on top of the CDK data-table.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
54
Q

CDK data-table example
first define headers
second define cell headers
then actual data

A

The first step to writing the data-table template is to define the columns. A column definition is specified via an with the cdkColumnDef directive, giving the column a name. Each column definition can contain a header-cell template (cdkHeaderCellDef), data-cell template (cdkCellDef), and footer-cell template (cdkFooterCellDef).

User name
{{row.a}}
User name

The set of columns defined represent the columns that are available to be rendered. The specific columns rendered in a given row, and their order, are specified on the row (see below).

Note that cdkCellDef exports the row context such that the row data can be referenced in the cell template. The directive also exports the same properties as ngFor (index, even, odd, first, last).

The next step is to define the table’s header-row (cdkHeaderRowDef), data-row (cdkRowDef), and footer-row (cdkFooterRowDef). Note that each of these are optional to include, depending on what type of rows you want rendered (e.g. if you do not need a footer row, simply do not add its definition).

These row templates accept the specific columns to be rendered via the name given to the cdkColumnDef.

The cdkRowDef also exports row context, which can be used for event and property bindings on the row element. Any content placed inside of the header row or data row template will be ignored, as the rendered content of the row comes from the cell templates described above.

Example: table with three columns

 User name 
 {{row.username}} 

 Age 
 {{row.age}} 

 Title 
 {{row.title}} 

The columns given on the row determine which cells are rendered and in which order. Thus, the columns can be set via binding to support dynamically changing the columns shown at run-time.

It is not required to display all the columns that are defined within the template, nor use the same ordering. For example, to display the table with only age and username and in that order, then the row and header definitions would be written as:

Event and property bindings can be added directly to the row element.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
55
Q

CDK data-table -table with event and class binding on each row

A

= 18”

(click)=”handleRowClick(row)”>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
56
Q

CDK data-table Styling columns

A

Each header and row cell will be provided a CSS class that includes its column. For example, cells that are displayed in the column name will be given the class cdk-column-name. This allows columns to be given styles that will match across the header and rows.

Since columns can be given any string for its name, its possible that it cannot be directly applied to the CSS class (e.g. *nameColumn!). In these cases, the special characters will be replaced by the - character. For example, cells container in a column named *nameColumn! will be given the class cdk-column–nameColumn-.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
57
Q

CDK data-table Connecting the table to a data source

A

Data is provided to the table through a DataSource. When the table receives a data source, it calls the DataSource’s connect() method which returns an observable that emits an array of data. Whenever the data source emits data to this stream, the table will render an update.

Because the data source provides this stream, it bears the responsibility of triggering table updates. This can be based on anything: websocket connections, user interaction, model updates, time-based intervals, etc. Most commonly, updates will be triggered by user interactions like sorting and pagination.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
58
Q

CDK data-table trackBy

A

To improve performance, a trackBy function can be provided to the table similar to Angular’s ngFor trackBy. This informs the table how to uniquely identify rows to track how the data changes with each update.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
59
Q

CDK data-table Alternate HTML to using native table

A

The CDK table does not require that you use a native HTML table. If you want to have full control over the style of the table, it may be easier to follow an alternative template approach that does not use the native table element tags.

This alternative approach replaces the native table element tags with the CDK table directive selectors. For example, becomes ; becomes . The following shows a previous example using this alternative template:

 User name 
 {{row.username}} 

 Age 
 {{row.age}} 

 Title 
 {{row.title}}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
60
Q

mat-table

A

The mat-table provides a Material Design styled data-table that can be used to display rows of data.

This table builds on the foundation of the CDK data-table and uses a similar interface for its data input and template, except that its element and attribute selectors will be prefixed with mat- instead of cdk-. For more information on the interface and a detailed look at how the table is implemented, see the guide covering the CDK data-table.

MatTable extends CdkTable

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
61
Q

Angular 6 Animations

A

Now that the Angular 6 project is ready we’re able to set up Angular Animations for this project. The first step is to add the following import statement in app.module.ts:
import { BrowserAnimationsModule } from ‘@angular/platform-browser/animations’;
Next we need to add BrowserAnimationsModule to the array which is assigned to the import property of the @NgModule decorator:
imports: [
BrowserModule,
BrowserAnimationsModule
],
This is making the content of BrowserAnimationsModule available to our application, so that we’re able to import animations in our components.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
62
Q

Implementing Angular animations

A

https://medium.com/codingthesmartway-com-blog/angular-6-animations-from-scratch-76e110cba5fb

Implementing AnimateComponent
Having prepared AppComponent we can now continue with the implementation of AnimateComponent. First, we need to include a div element in animate.component.html which is displaying the rectangle which is being animated.

<div></div>

The corresponding CSS code for the myblock class needs to be inserted into animate.component.css:
.myblock {
background-color: green;
width: 300px;
height: 250px;
border-radius: 5px;
margin: 5rem;
}
Finally we’re able to define the animations / transitions in file animate.component.ts:
import { Component, OnInit, Input } from ‘@angular/core’;
import { trigger, state, style, animate, transition } from ‘@angular/animations’;
@Component({
selector: ‘app-animate’,
templateUrl: ‘./animate.component.html’,
styleUrls: [’./animate.component.css’],
animations: [
trigger(‘changeState’, [
state(‘state1’, style({
backgroundColor: ‘green’,
transform: ‘scale(1)’
})),
state(‘state2’, style({
backgroundColor: ‘red’,
transform: ‘scale(1.5)’
})),
transition(‘=>state1’, animate(‘300ms’)),
transition(‘
=>state2’, animate(‘2000ms’))
])
]
})
export class AnimateComponent implements OnInit {
@Input() currentState;
constructor() { }
ngOnInit() {
}
}
Note, that we’re first importing trigger, state, style, animate, and transition from the @angular/animations package. Having imported those assets gives us the possibility of defining the animations we’d like to include in that components.
To define animations the animations property of the @Component decorator is used. By using the function trigger inside the array which is assigned to that property we’re defining animations which are used if the changeState trigger is activated (each time the currentState value changes). Therefore the string value changeState is passed into the call of that function.
The second parameter is an array again which is consisting of four element. For the first two items the state function is called and the style is defined which is used for state1 and state2. For each state we’re setting a different background color and a different scale.
As the last two elements we’re defining transitions (by using the transition function). The first transition is defined by the string *=>state1. This simply means that this transition is invoked each time state1 is set regardless of the previous state. By using the animate function and passing in the string value 300ms we’re defining that the transition has a duration of 300 milliseconds.
In a similar way the second transition is defined. This way we’re defining the transition which is taking place if state2 is entered.
Conclusion
Angular Animations are a powerful way to implement sophisticated and compelling animations for your Angular single page web application. Having followed this tutorial you have now a profound understanding of how to setup and apply Angular Animations in your Angular 6 project.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
63
Q

table expandable example

A

import {Component} from ‘@angular/core’;
import {animate, state, style, transition, trigger} from ‘@angular/animations’;

/**
* @title Table with expandable rows
/
@Component({
selector: ‘table-expandable-rows-example’,
styleUrls: [‘table-expandable-rows-example.css’],
templateUrl: ‘table-expandable-rows-example.html’,
animations: [
trigger(‘detailExpand’, [
state(‘collapsed’, style({height: ‘0px’, minHeight: ‘0’})),
state(‘expanded’, style({height: ‘
’})),
transition(‘expanded <=> collapsed’, animate(‘225ms cubic-bezier(0.4, 0.0, 0.2, 1)’)),
]),
],
})
export class TableExpandableRowsExample {
dataSource = ELEMENT_DATA;
columnsToDisplay = [‘name’, ‘weight’, ‘symbol’, ‘position’];
expandedElement: PeriodicElement | null;
}

export interface PeriodicElement {
  name: string;
  position: number;
  weight: number;
  symbol: string;
  description: string;
}

const ELEMENT_DATA: PeriodicElement[] = [
{
position: 1,
name: ‘Hydrogen’,
weight: 1.0079,
symbol: ‘H’,
description: Hydrogen is a chemical element with symbol H and atomic number 1. With a standard atomic weight of 1.008, hydrogen is the lightest element on the periodic table.
}, {
position: 2,
name: ‘Helium’,
weight: 4.0026,
symbol: ‘He’,
description: Helium is a chemical element with symbol He and atomic number 2. It is a colorless, odorless, tasteless, non-toxic, inert, monatomic gas, the first in the noble gas group in the periodic table. Its boiling point is the lowest among all the elements.
}, {
position: 3,
name: ‘Lithium’,
weight: 6.941,
symbol: ‘Li’,
description: Lithium is a chemical element with symbol Li and atomic number 3. It is a soft, silvery-white alkali metal. Under standard conditions, it is the lightest metal and the lightest solid element.
}, {
position: 4,
name: ‘Beryllium’,
weight: 9.0122,
symbol: ‘Be’,
description: Beryllium is a chemical element with symbol Be and atomic number 4. It is a relatively rare element in the universe, usually occurring as a product of the spallation of larger atomic nuclei that have collided with cosmic rays.
}, {
position: 5,
name: ‘Boron’,
weight: 10.811,
symbol: ‘B’,
description: Boron is a chemical element with symbol B and atomic number 5. Produced entirely by cosmic ray spallation and supernovae and not by stellar nucleosynthesis, it is a low-abundance element in the Solar system and in the Earth's crust.
}, {
position: 6,
name: ‘Carbon’,
weight: 12.0107,
symbol: ‘C’,
description: Carbon is a chemical element with symbol C and atomic number 6. It is nonmetallic and tetravalent—making four electrons available to form covalent chemical bonds. It belongs to group 14 of the periodic table.
}, {
position: 7,
name: ‘Nitrogen’,
weight: 14.0067,
symbol: ‘N’,
description: Nitrogen is a chemical element with symbol N and atomic number 7. It was first discovered and isolated by Scottish physician Daniel Rutherford in 1772.
}, {
position: 8,
name: ‘Oxygen’,
weight: 15.9994,
symbol: ‘O’,
description: Oxygen is a chemical element with symbol O and atomic number 8. It is a member of the chalcogen group on the periodic table, a highly reactive nonmetal, and an oxidizing agent that readily forms oxides with most elements as well as with other compounds.
}, {
position: 9,
name: ‘Fluorine’,
weight: 18.9984,
symbol: ‘F’,
description: Fluorine is a chemical element with symbol F and atomic number 9. It is the lightest halogen and exists as a highly toxic pale yellow diatomic gas at standard conditions.
}, {
position: 10,
name: ‘Neon’,
weight: 20.1797,
symbol: ‘Ne’,
description: Neon is a chemical element with symbol Ne and atomic number 10. It is a noble gas. Neon is a colorless, odorless, inert monatomic gas under standard conditions, with about two-thirds the density of air.
},
];

/** Copyright 2019 Google LLC. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license */

html file:

 {{column}} 
 {{element[column]}} 

  <div class="example-element-detail">
    <div class="example-element-diagram">
      <div class="example-element-position"> {{element.position}} </div>
      <div class="example-element-symbol"> {{element.symbol}} </div>
      <div class="example-element-name"> {{element.name}} </div>
      <div class="example-element-weight"> {{element.weight}} </div>
    </div>
    <div class="example-element-description">
      {{element.description}}
      <span class="example-element-description-attribution"> -- Wikipedia </span>
    </div>
  </div>
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
64
Q

What’s the difference between [style] and [ngStyle] in Angular
style - for dynamic styling in angular but one property at a time
ngstyle - object with all the styling properties

A

https://blog.angulartraining.com/whats-the-difference-between-style-and-ngstyle-in-angular-68a3301c2ae6

When you need to apply dynamic styles to a HTML element using Angular, there are different options to consider.
The first and most obvious solution is to use the regular style or class HTML attributes along with Angular data-bindings, which looks like this:

<div>
The phone number you entered does not match the expected format
</div>

The above code would style the div using a color value set on the errorMessageColor property of your component. Thanks to the data binding, whenever that property changes, the div would get a new color.
You can make the above example even more powerful using the ternary operator in your expression to express a conditional styling:

<div>
The phone number you entered does not match the expected format
</div>

The above example assumes that hasError can evaluate to true, which is convenient since in Javascript anything that is not null or undefined would work. As a result, if hasError is something that isn’t null or undefined or false, then the message will show up in red color, otherwise it will be black.
This is great but it can get quite verbose if you want to apply multiple styles to the same element:

<div>
The phone number you entered does not match the expected format
</div>

In that case, using a CSS class is a much better option as you can refactor those CSS properties in one place and possibly reuse them on other HTML elements.
Sometimes, you might need very specific CSS properties based on different conditions though. That’s where ngStyle comes into play. With ngStyle, you can bind to an object that expresses as many conditions and cases as you need:

<div>
The phone number you entered does not match the expected format
</div>

And then in your component code:
this.currentStyles = {
‘font-style’: this.canSave ? ‘italic’ : ‘normal’,
‘color’: this.hasError ? ‘red’ : ‘black’,
‘font-size’: this.hasError ? ‘24px’ : ‘12px’
};
Now you can express as many different styles as needed. ngStyle is an Angular directive that gives you the flexibility to do this, where as style is a regular HTML property to which you can only bind values one by one. That’s the difference between the two of them.
Note that the same distinction of behavior applies between class and ngClass, where the former is meant to be used for single bindings, and the latter can be used to bind to a decision object similar to the one showed above for ngStyle.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
65
Q

Angular Material Icons

A

https://material.io/resources/icons/?icon=email&style=baseline

example for email:

<i>
email
</i>

<i>
email
</i>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
66
Q

I can not apply style on ng-container

A
the below will not work:
   <div class="responsibility-chip">
                            {{ responsibility }}
                        </div>
-------------------
below will work:   

<div>
{{ responsibility }}
</div>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
67
Q

adding tooltip to a button

A

Action

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
68
Q

mat-form-field

A

is a component used to wrap several Angular Material components and apply common Text field styles such as the underline, floating label, and hint messages.

In this document, “form field” refers to the wrapper component and “form field control” refers to the component that the is wrapping (e.g. the input, textarea, select, etc.)

The following Angular Material components are designed to work inside a :

&

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
69
Q

mat-form-field example

A

<div>

Input

<br></br>

Select

Option

<br></br>

Textarea

</div>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
70
Q

Form field appearance variants

A

The mat-form-field supports 4 different appearance variants which can be set via the appearance input. The legacy appearance is the default style that the mat-form-field has traditionally had. It shows the input box with an underline underneath it. The standard appearance is a slightly updated version of the legacy appearance that has spacing that is more consistent with the fill and outline appearances. The fill appearance displays the form field with a filled background box in addition to the underline. Finally the outline appearance shows the form field with a border all the way around, not just an underline.

There are a couple differences to be aware of between the legacy appearance and the newer standard, fill, and outline appearances. The matPrefix and matSuffix elements are center aligned by default for the newer appearances. The Material Design spec shows this as being the standard way to align prefix and suffix icons in the newer appearance variants. We do not recommend using text prefix and suffixes in the new variants because the label and input do not have the same alignment. It is therefore impossible to align the prefix or suffix in a way that looks good when compared with both the label and input text.

The second important difference is that the standard, fill, and outline appearances do not promote placeholders to labels. For the legacy appearance specifying will result in a floating label being added to the mat-form-field. For the newer variants it will just add a normal placeholder to the input. If you want a floating label, add a to the mat-form-field.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
71
Q

mat-form-field appreance example

A

<p>

Legacy form field

sentiment_very_satisfied
Hint

</p>

<p>

Standard form field

sentiment_very_satisfied
Hint

</p>

<p>

Fill form field

sentiment_very_satisfied
Hint

</p>

<p>

Outline form field

sentiment_very_satisfied
Hint

</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
72
Q

matSuffix/matPrefix

A

where to display mat icon

Fill form field

sentiment_very_satisfied
Hint
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
73
Q

mat-form-field Floating label

A

The floating label is a text label displayed on top of the form field control when the control does not contain any text or when does not show any option text. By default, when text is present the floating label floats above the form field control. The label for a form field can be specified by adding a mat-label element.

In the legacy version of the (one that has no appearance attribute or has appearance=”legacy”) if a label is not specified, the placeholder attribute on the form control is promoted to a label. If a label is specified, the placeholder will be displayed as a normal placeholder. The placeholder will never be promoted to a label for standard, fill, and outline form fields. If you want to create a legacy form field with a placeholder but no label, you will need to specify an empty label to prevent the placeholder from being promoted.

If the form field control is marked with a required attribute, an asterisk will be appended to the label to indicate the fact that it is a required field. If unwanted, this can be disabled by setting the hideRequiredMarker property on

The floatLabel property of can be used to change this default floating behavior. It can set to never to hide the label instead of float it when text is present in the form field control. It can be set to always to float the label even when no text is present in the form field control. It can also be set to auto to restore the default behavior.

<div>

Hide required marker
<div>
Float label:

Auto
Always

</div>

Both a label and a placeholder

-- None --
Option

favorite <b> Fancy</b> <i> label</i>

</div>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
74
Q

changing the float label default behavior

A

The floating label behavior can be adjusted globally by providing a value for MAT_FORM_FIELD_DEFAULT_OPTIONS in your application’s root module. Like the floatLabel input, the option can be either set to always, never, or auto.

@NgModule({
  providers: [
    {provide: MAT_FORM_FIELD_DEFAULT_OPTIONS, useValue: {floatLabel: 'always'}}
  ]
})
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
75
Q

Hint labels -mat-hint

A

Hint labels are additional descriptive text that appears below the form field’s underline. A can have up to two hint labels; one start-aligned (left in an LTR language, right in RTL), and one end-aligned.

Hint labels are specified in one of two ways: either by using the hintLabel property of , or by adding a element inside the form field. When adding a hint via the hintLabel property, it will be treated as the start hint. Hints added via the hint element can be added to either side by setting the align property on to either start or end. Attempting to add multiple hints to the same side will raise an error.

<div>

Enter some input

{{input.value?.length || 0}}/10

Select me

Option

Here's the dropdown arrow ^

</div>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
76
Q

Error messages and mat-form-field

A

Error messages can be shown under the form field underline by adding mat-error elements inside the form field. Errors are hidden initially and will be displayed on invalid form fields after the user has interacted with the element or the parent form has been submitted. Since the errors occupy the same space as the hints, the hints are hidden when the errors are shown.

If a form field can have more than one error state, it is up to the consumer to toggle which messages should be displayed. This can be done with CSS, ngIf or ngSwitch. Multiple error messages can be shown at the same time if desired, but the only reserves enough space to display one error message at a time. Ensuring that enough space is available to display multiple errors is up to the user.

<div>

Enter your email

{{getErrorMessage()}}

</div>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
77
Q

Prefix & suffix

A

Custom content can be included before and after the input tag, as a prefix or suffix. It will be included within the visual container that wraps the form control as per the Material specification.

Adding the matPrefix directive to an element inside the will designate it as the prefix. Similarly, adding matSuffix will designate it as the suffix.

<div>

Enter your password

{{hide ? 'visibility_off' : 'visibility'}}

Amount

<span>$</span>
<span>.00</span>

</div>

78
Q

mat-icon-button

A

Enter your password

{{hide ? 'visibility_off' : 'visibility'}}
79
Q

conditionally changing the mat icon button

A

Enter your password

{{hide ? 'visibility_off' : 'visibility'}}
80
Q

Custom form field controls

A

In addition to the form field controls that Angular Material provides, it is possible to create custom form field controls that work with in the same way. For additional information on this see the guide on Creating Custom mat-form-field Controls.

https://material.angular.io/guide/creating-a-custom-form-field-control

81
Q

mat-form-field theming

A

has a color property which can be set to primary, accent, or warn. This will set the color of the form field underline and floating label based on the theme colors of your app.

inherits its font-size from its parent element. This can be overridden to an explicit size using CSS. We recommend a specificity of at least 1 element + 1 class.

mat-form-field.mat-form-field {
font-size: 16px;
}

Color

  Primary
  Accent
  Warn

Font size

<span>px</span>
Min size: 10px
82
Q

dynamically setting the font size

A
83
Q

mat-select

A

is a form control for selecting a value from a set of options, similar to the native element. You can read more about selects in the Material Design spec. It is designed to work inside of a element.

To add options to the select, add elements to the . Each has a value property that can be used to set the value that will be selected if the user chooses this option. The content of the is what will be shown to the user.

Angular Material also supports use of the native element inside of . The native control has several performance, accessibility, and usability advantages. See the documentation for form-field for more information.

To use a native select inside , add the matNativeControl attribute to the element.

84
Q

mat-select example

A

HTML:

<h4>Basic mat-select</h4>

Favorite food

  {{food.viewValue}}


TS
import {Component} from ‘@angular/core’;

interface Food {
value: string;
viewValue: string;
}

/**
 * @title Basic select
 */
@Component({
  selector: 'select-overview-example',
  templateUrl: 'select-overview-example.html',
  styleUrls: ['select-overview-example.css'],
})
export class SelectOverviewExample {
  foods: Food[] = [
    {value: 'steak-0', viewValue: 'Steak'},
    {value: 'pizza-1', viewValue: 'Pizza'},
    {value: 'tacos-2', viewValue: 'Tacos'}
  ];
}
85
Q

select with matNativeControl attribute

A

<h4>Basic native select</h4>

Cars

Volvo
Saab
Mercedes
Audi
86
Q

mat-select Getting and setting the select value

A

The supports 2-way binding to the value property without the need for Angular forms.
HTML:

Select an option

None
Option 1
Option 2
Option 3

<p>You selected: {{selected}}</p>

TS:
import {Component} from ‘@angular/core’;

/** @title Select with 2-way value binding */
@Component({
  selector: 'select-value-binding-example',
  templateUrl: 'select-value-binding-example.html',
  styleUrls: ['select-value-binding-example.css'],
})
export class SelectValueBindingExample {
  selected = 'option2';
}
87
Q

and support all of the form directives

A

Both and support all of the form directives from the core FormsModule (NgModel) and ReactiveFormsModule (FormControl, FormGroup, etc.) As with native , also supports a compareWith function. (Additional information about using a custom compareWith function can be found in the Angular forms documentation).

88
Q

mat-select in forms module

A

HTML:

<h4>mat-select</h4>

Favorite food

    {{food.viewValue}}

<p> Selected food: {{selectedValue}} </p>

<h4>native html select</h4>

Favorite car

    {{car.viewValue}}

<p> Selected car: {{selectedCar}} </p>

TS:
import {Component} from ‘@angular/core’;

interface Food {
value: string;
viewValue: string;
}

interface Car {
value: string;
viewValue: string;
}

/**
 * @title Select in a form
 */
@Component({
  selector: 'select-form-example',
  templateUrl: 'select-form-example.html',
  styleUrls: ['select-form-example.css'],
})
export class SelectFormExample {
  selectedValue: string;
  selectedCar: string;

foods: Food[] = [
{value: ‘steak-0’, viewValue: ‘Steak’},
{value: ‘pizza-1’, viewValue: ‘Pizza’},
{value: ‘tacos-2’, viewValue: ‘Tacos’}
];

cars: Car[] = [
{value: ‘volvo’, viewValue: ‘Volvo’},
{value: ‘saab’, viewValue: ‘Saab’},
{value: ‘mercedes’, viewValue: ‘Mercedes’}
];
}

89
Q

and using matformfied features

A

There are a number of features that can be used with both and . These include error messages, hint text, prefix & suffix, and theming. For additional information about these features, see the form field documentation.

90
Q

using , and in with

A

HTML:

<h4>mat select</h4>

Favorite animal

--

  {{animal.name}}

Please choose an animal
{{animalControl.value?.sound}}

<h4>native html select</h4>

Select your car (required)

Saab
Mercedes
Audi

This field is required

You can pick up your favorite car here

TS:
import {Component} from ‘@angular/core’;
import {FormControl, Validators} from ‘@angular/forms’;

interface Animal {
name: string;
sound: string;
}

/** @title Select with form field features */
@Component({
  selector: 'select-hint-error-example',
  templateUrl: 'select-hint-error-example.html',
  styleUrls: ['select-hint-error-example.css'],
})
export class SelectHintErrorExample {
  animalControl = new FormControl('', Validators.required);
  selectFormControl = new FormControl('', Validators.required);
  animals: Animal[] = [
    {name: 'Dog', sound: 'Woof!'},
    {name: 'Cat', sound: 'Meow!'},
    {name: 'Cow', sound: 'Moo!'},
    {name: 'Fox', sound: 'Wa-pa-pa-pa-pa-pa-pow!'},
  ];
}

here we are assinging the value of mat-select to the whole object instead of just value property

  {{animal.name}}

as we want to read an attribute later {{animalControl.value?.sound}}

other way to do the samething:

Favorite animal

--

  {{animal.name}}

Please choose an animal
{{animalControl.value}}

91
Q

using ngIf for showing errors in reactive forms module

A

Select your car (required)

Saab
Mercedes
Audi

This field is required

You can pick up your favorite car here

92
Q

[formControl] in this need not have the values for options, this could be another property

A

Favorite animal

--

  {{animal.name}}

Please choose an animal
{{animalControl.value?.sound}}

TS:
import {Component} from ‘@angular/core’;
import {FormControl, Validators} from ‘@angular/forms’;

interface Animal {
name: string;
sound: string;
}

/** @title Select with form field features */
@Component({
  selector: 'select-hint-error-example',
  templateUrl: 'select-hint-error-example.html',
  styleUrls: ['select-hint-error-example.css'],
})
export class SelectHintErrorExample {
  animalControl = new FormControl('', Validators.required);
  selectFormControl = new FormControl('', Validators.required);
  animals: Animal[] = [
    {name: 'Dog', sound: 'Woof!'},
    {name: 'Cat', sound: 'Meow!'},
    {name: 'Cow', sound: 'Moo!'},
    {name: 'Fox', sound: 'Wa-pa-pa-pa-pa-pa-pow!'},
  ];
}
93
Q

Setting a static placeholder

A

The placeholder is text shown when the label is floating but the is empty. It is used to give the user an additional hint about the value they should select. The placeholder can be specified by setting the placeholder attribute on the element. In some cases that may use the placeholder as the label (see the form field label documentation).

94
Q

Disabling the select or individual options using Reactive forms module

A
It is possible to disable the entire select or individual options in the select by using the disabled property on the  or  and the  or  elements respectively.
HTML:
<p>
  Disable select
</p>

<h4>mat-select</h4>

Choose an option

Option 1
Option 2 (disabled)
Option 3

<h4>native html select</h4>

Choose an option

Volvo
Saab
Mercedes
Audi

TS:
import {Component} from ‘@angular/core’;
import {FormControl} from ‘@angular/forms’;

/** @title Disabled select */
@Component({
  selector: 'select-disabled-example',
  templateUrl: 'select-disabled-example.html',
  styleUrls: ['select-disabled-example.css'],
})
export class SelectDisabledExample {
  disableSelect = new FormControl(false);
}
95
Q

enabling disabling check box with reactive forms module

A

<p>
Disable select
</p>

in ts:
import {Component} from ‘@angular/core’;
import {FormControl} from ‘@angular/forms’;

/** @title Disabled select */
@Component({
  selector: 'select-disabled-example',
  templateUrl: 'select-disabled-example.html',
  styleUrls: ['select-disabled-example.css'],
})
export class SelectDisabledExample {
  disableSelect = new FormControl(false);
}
96
Q

Resetting the select value

A

If you want one of your options to reset the select’s value, you can omit specifying its value.

in HTML:

<h4>mat-select</h4>

State

None
{{state}}

<h4>native html select</h4>

Select your car

Volvo
Saab
Mercedes
Audi

in TS:
import {Component} from ‘@angular/core’;

/** @title Select with reset option */
@Component({
selector: ‘select-reset-example’,
templateUrl: ‘select-reset-example.html’,
styleUrls: [‘select-reset-example.css’],
})
export class SelectResetExample {
states: string[] = [
‘Alabama’, ‘Alaska’, ‘Arizona’, ‘Arkansas’, ‘California’, ‘Colorado’, ‘Connecticut’, ‘Delaware’,
‘Florida’, ‘Georgia’, ‘Hawaii’, ‘Idaho’, ‘Illinois’, ‘Indiana’, ‘Iowa’, ‘Kansas’, ‘Kentucky’,
‘Louisiana’, ‘Maine’, ‘Maryland’, ‘Massachusetts’, ‘Michigan’, ‘Minnesota’, ‘Mississippi’,
‘Missouri’, ‘Montana’, ‘Nebraska’, ‘Nevada’, ‘New Hampshire’, ‘New Jersey’, ‘New Mexico’,
‘New York’, ‘North Carolina’, ‘North Dakota’, ‘Ohio’, ‘Oklahoma’, ‘Oregon’, ‘Pennsylvania’,
‘Rhode Island’, ‘South Carolina’, ‘South Dakota’, ‘Tennessee’, ‘Texas’, ‘Utah’, ‘Vermont’,
‘Virginia’, ‘Washington’, ‘West Virginia’, ‘Wisconsin’, ‘Wyoming’
];
}

97
Q

Creating groups of options

A

The element can be used to group common options under a subheading. The name of the group can be set using the label property of . Like individual elements, an entire can be disabled or enabled by setting the disabled property on the group.

HTML:

<h4>mat-select</h4>

Pokemon

-- None --

    {{pokemon.viewValue}}

<h4>native html select</h4>

Cars

  volvo
  Saab

  Mercedes
  Audi

TS:
import {Component} from ‘@angular/core’;
import {FormControl} from ‘@angular/forms’;

interface Pokemon {
value: string;
viewValue: string;
}

interface PokemonGroup {
  disabled?: boolean;
  name: string;
  pokemon: Pokemon[];
}
/** @title Select with option groups */
@Component({
  selector: 'select-optgroup-example',
  templateUrl: 'select-optgroup-example.html',
  styleUrls: ['select-optgroup-example.css'],
})
export class SelectOptgroupExample {
  pokemonControl = new FormControl();
  pokemonGroups: PokemonGroup[] = [
    {
      name: 'Grass',
      pokemon: [
        {value: 'bulbasaur-0', viewValue: 'Bulbasaur'},
        {value: 'oddish-1', viewValue: 'Oddish'},
        {value: 'bellsprout-2', viewValue: 'Bellsprout'}
      ]
    },
    {
      name: 'Water',
      pokemon: [
        {value: 'squirtle-3', viewValue: 'Squirtle'},
        {value: 'psyduck-4', viewValue: 'Psyduck'},
        {value: 'horsea-5', viewValue: 'Horsea'}
      ]
    },
    {
      name: 'Fire',
      disabled: true,
      pokemon: [
        {value: 'charmander-6', viewValue: 'Charmander'},
        {value: 'vulpix-7', viewValue: 'Vulpix'},
        {value: 'flareon-8', viewValue: 'Flareon'}
      ]
    },
    {
      name: 'Psychic',
      pokemon: [
        {value: 'mew-9', viewValue: 'Mew'},
        {value: 'mewtwo-10', viewValue: 'Mewtwo'},
      ]
    }
  ];
}
98
Q

Multiple selection

A

defaults to single-selection mode, but can be configured to allow multiple selection by setting the multiple property. This will allow the user to select multiple values at once. When using the in multiple selection mode, its value will be a sorted list of all selected values rather than a single value.

Using multiple selection with a native select element () is discouraged inside , as the inline listbox appearance is inconsistent with other Material Design components.

HTML:

Toppings

{{topping}}

TS:
import {Component} from ‘@angular/core’;
import {FormControl} from ‘@angular/forms’;

/** @title Select with multiple selection */
@Component({
  selector: 'select-multiple-example',
  templateUrl: 'select-multiple-example.html',
  styleUrls: ['select-multiple-example.css'],
})
export class SelectMultipleExample {
  toppings = new FormControl();
  toppingList: string[] = ['Extra cheese', 'Mushroom', 'Onion', 'Pepperoni', 'Sausage', 'Tomato'];
}
99
Q

Customizing the trigger label - This is awesome

A

If you want to display a custom trigger label inside a , you can use the element.
html:

Toppings

  {{toppings.value ? toppings.value[0] : ''}}
  <span> 1" class="example-additional-selection">
    (+{{toppings.value.length - 1}} {{toppings.value?.length === 2 ? 'other' : 'others'}})
  </span>

{{topping}}

TS:
import {Component} from ‘@angular/core’;
import {FormControl} from ‘@angular/forms’;

/** @title Select with custom trigger text */
@Component({
  selector: 'select-custom-trigger-example',
  templateUrl: 'select-custom-trigger-example.html',
  styleUrls: ['select-custom-trigger-example.css'],
})
export class SelectCustomTriggerExample {
  toppings = new FormControl();

toppingList: string[] = [‘Extra cheese’, ‘Mushroom’, ‘Onion’, ‘Pepperoni’, ‘Sausage’, ‘Tomato’];
}

CSS:
.example-additional-selection {
  opacity: 0.75;
  font-size: 0.75em;
}
100
Q

Disabling the ripple effect

A

By default, when a user clicks on a , a ripple animation is shown. This can be disabled by setting the disableRipple property on .

HTML:

Select an option

Option 1
Option 2
Option 3

TS:
import {Component} from ‘@angular/core’;

/** @title Select with no option ripple */
@Component({
  selector: 'select-no-ripple-example',
  templateUrl: 'select-no-ripple-example.html',
  styleUrls: ['select-no-ripple-example.css'],
})
export class SelectNoRippleExample {}
101
Q

Adding custom styles to the dropdown panel

A

In order to facilitate easily styling the dropdown panel, has a panelClass property which can be used to apply additional CSS classes to the dropdown panel.

HTML:

Panel color

Red
Green
Blue

TS:
import {Component, ViewEncapsulation} from ‘@angular/core’;
import {FormControl} from ‘@angular/forms’;

/**
 * @title Select with custom panel styling
 */
@Component({
  selector: 'select-panel-class-example',
  templateUrl: 'select-panel-class-example.html',
  styleUrls: ['select-panel-class-example.css'],
  // Encapsulation has to be disabled in order for the
  // component style to apply to the select panel.
  encapsulation: ViewEncapsulation.None,
})
export class SelectPanelClassExample {
  panelColor = new FormControl('red');
}

CSS:
.example-panel-red.mat-select-panel {
background: rgba(255, 0, 0, 0.5);
}

.example-panel-green.mat-select-panel {
background: rgba(0, 255, 0, 0.5);
}

.example-panel-blue.mat-select-panel {
background: rgba(0, 0, 255, 0.5);
}

102
Q

setting class dynamically

A

CSS:
.example-panel-red.mat-select-panel {
background: rgba(255, 0, 0, 0.5);
}

.example-panel-green.mat-select-panel {
background: rgba(0, 255, 0, 0.5);
}

.example-panel-blue.mat-select-panel {
background: rgba(0, 0, 255, 0.5);
}

103
Q

Changing when error messages are shown

A

The allows you to associate error messages with your or . By default, these error messages are shown when the control is invalid and either the user has interacted with (touched) the element or the parent form has been submitted. If you wish to override this behavior (e.g. to show the error as soon as the invalid control is dirty or when a parent form group is invalid), you can use the errorStateMatcher property of the . The property takes an instance of an ErrorStateMatcher object. An ErrorStateMatcher must implement a single method isErrorState which takes the FormControl for this as well as the parent form and returns a boolean indicating whether errors should be shown. (true indicating that they should be shown, and false indicating that they should not.)

HTML:

<h4>mat-select</h4>

Choose one

Clear
Valid option
Invalid option

Errors appear instantly!
You must make a selection

Your selection is invalid

<h4>native html select</h4>

Choose one

Valid option
Invalid option

You must make a selection

Your selection is invalid

TS:
import {Component} from ‘@angular/core’;
import {FormControl, FormGroupDirective, NgForm, Validators} from ‘@angular/forms’;
import {ErrorStateMatcher} from ‘@angular/material/core’;

/** Error when invalid control is dirty, touched, or submitted. */
export class MyErrorStateMatcher implements ErrorStateMatcher {
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    const isSubmitted = form &amp;&amp; form.submitted;
    return !!(control &amp;&amp; control.invalid &amp;&amp; (control.dirty || control.touched || isSubmitted));
  }
}

/** @title Select with a custom ErrorStateMatcher */
@Component({
selector: ‘select-error-state-matcher-example’,
templateUrl: ‘select-error-state-matcher-example.html’,
styleUrls: [‘select-error-state-matcher-example.css’],
})
export class SelectErrorStateMatcherExample {
selected = new FormControl(‘valid’, [
Validators.required,
Validators.pattern(‘valid’),
]);

selectFormControl = new FormControl(‘valid’, [
Validators.required,
Validators.pattern(‘valid’),
]);

nativeSelectFormControl = new FormControl(‘valid’, [
Validators.required,
Validators.pattern(‘valid’),
]);

  matcher = new MyErrorStateMatcher();
}

A global error state matcher can be specified by setting the ErrorStateMatcher provider. This applies to all inputs. For convenience, ShowOnDirtyErrorStateMatcher is available in order to globally cause input errors to show when the input is dirty and invalid.

@NgModule({
  providers: [
    {provide: ErrorStateMatcher, useClass: ShowOnDirtyErrorStateMatcher}
  ]
})
104
Q

Keyboard interaction

A

DOWN_ARROW: Focus next option
UP_ARROW: Focus previous option
ENTER or SPACE: Select focused item

105
Q

shown when

A

By default, these error messages are shown when the control is invalid and either the user has interacted with (touched) the element or the parent form has been submitted.

106
Q

Error: Cannot change multiple mode of select after initialization

A

This error is thrown if you attempt to bind the multiple property on to a dynamic value. (e.g. [multiple]=”isMultiple” where the value of isMultiple changes over the course of the component’s lifetime). If you need to change this dynamically, use ngIf or ngSwitch instead:

107
Q

Error: Value must be an array in multiple-selection mode

A

This error is thrown if you attempt to assign a value other than null, undefined, or an array to a . For example, something like mySelect.value = ‘option1’. What you likely meant to do was mySelect.value = [‘option1’].

108
Q

Error: compareWith must be a function

A

This error occurs if you attempt to assign something other than a function to the compareWith property. For more information on proper usage of compareWith see the Angular forms documentation).

109
Q

ngx-toastr

A

https://www.npmjs.com/package/ngx-toastr

Step 1: add css
copy toast css to your project.
If you are using sass you can import the css.
// regular style toast 
@import '~ngx-toastr/toastr';
// bootstrap style toast 
// or import a bootstrap 4 alert styled design (SASS ONLY) 
// should be after your bootstrap imports, it uses bs4 variables, mixins, functions 
@import '~ngx-toastr/toastr-bs4-alert';
// if you'd like to use it without importing all of bootstrap it requires 
@import '~bootstrap/scss/functions';
@import '~bootstrap/scss/variables';
@import '~bootstrap/scss/mixins';
@import '~ngx-toastr/toastr-bs4-alert';

If you are using angular-cli you can add it to your angular.json
“styles”: [
“styles.scss”,
“node_modules/ngx-toastr/toastr.css” // try adding ‘../’ if you’re using angular cli before 6
]
step 2: add ToastrModule to app NgModule, make sure you have BrowserAnimationsModule as well
import { CommonModule } from ‘@angular/common’;
import { BrowserAnimationsModule } from ‘@angular/platform-browser/animations’;

import { ToastrModule } from ‘ngx-toastr’;

@NgModule({
  imports: [
    CommonModule,
    BrowserAnimationsModule, // required animations module
    ToastrModule.forRoot() // ToastrModule added
  ],
  bootstrap: [App],
  declarations: [App]
})
class MainModule {}

Use:
import { ToastrService } from ‘ngx-toastr’;

@Component({...})
export class YourComponent {
  constructor(private toastr: ToastrService) {}

showSuccess() {
this.toastr.success(‘Hello world!’, ‘Toastr fun!’);
}
}

110
Q

ngOnInit

A

constructor() is the default method in the Component life cycle and is used for dependency injection. Constructor is a Typescript Feature. ngOnInit() is called after the constructor and ngOnInit is called after the first

ngOnChanges.

the service calls are issued here in ngOnInit:
 ngOnInit(): void {
    this.getCurrentUser();
    this.getAllFiles();
    this.getResourceTypes();
    this.getInitiatives();
    this.getTagsList();
    this.getRecentlyAddedFiles();
    this.getRecentlyViewedFiles();
    this.getMostPopularFiles();
    this.getFileTypes();
    this.getWebPlacement();
  }
111
Q

datepicker

A

The datepicker allows users to enter a date either through text input, or by choosing a date from the calendar. It is made up of several components and directives that work together

Choose a date

112
Q

Connecting a datepicker to an input

A

A datepicker is composed of a text input and a calendar pop-up, connected via the matDatepicker property on the text input.

An optional datepicker toggle button is available. A toggle can be added to the example above:

This works exactly the same with an input that is part of an and the toggle can easily be used as a prefix or suffix on the material input:

If you want to customize the icon that is rendered inside the mat-datepicker-toggle, you can do so by using the matDatepickerToggleIcon directive:

Choose a date

keyboard_arrow_down
113
Q

mat-datepicker Setting the calendar starting view

A

The startView property of can be used to set the view that will show up when the calendar first opens. It can be set to month, year, or multi-year; by default it will open to month view.

The month, year, or range of years that the calendar opens to is determined by first checking if any date is currently selected, if so it will open to the month or year containing that date. Otherwise it will open to the month or year containing today’s date. This behavior can be overridden by using the startAt property of . In this case the calendar will open to the month or year containing the startAt date.

HTML:

Choose a date

TS:
import {Component} from ‘@angular/core’;

/** @title Datepicker start date */
@Component({
  selector: 'datepicker-start-view-example',
  templateUrl: 'datepicker-start-view-example.html',
  styleUrls: ['datepicker-start-view-example.css'],
})
export class DatepickerStartViewExample {
  startDate = new Date(1990, 0, 1);
}
114
Q

mat-datepicker Watching the views for changes on selected years and months

A

When a year or a month is selected in multi-year and year views respectively, the yearSelected and monthSelected outputs emit a normalized date representing the chosen year or month. By “normalized” we mean that the dates representing years will have their month set to January and their day set to the 1st. Dates representing months will have their day set to the 1st of the month. For example, if is configured to work with javascript native Date objects, the yearSelected will emit new Date(2017, 0, 1) if the user selects 2017 in multi-year view. Similarly, monthSelected will emit new Date(2017, 1, 1) if the user selects February in year view and the current date value of the connected was set to something like new Date(2017, MM, dd) when the calendar was opened (the month and day are irrelevant in this case).

Notice that the emitted value does not affect the current value in the connected , which is only bound to the selection made in the month view. So if the end user closes the calendar after choosing a year in multi-view mode (by pressing the ESC key, for example), the selected year, emitted by yearSelected output, will not cause any change in the value of the date in the associated .

The following example uses yearSelected and monthSelected outputs to emulate a month and year picker (if you’re not familiar with the usage of MomentDateAdapter and MAT_DATE_FORMATS you can read more about them below in this document to fully understand the example).

HTML:

Month and Year

TS:
import {Component} from ‘@angular/core’;
import {FormControl} from ‘@angular/forms’;
import {MomentDateAdapter, MAT_MOMENT_DATE_ADAPTER_OPTIONS} from ‘@angular/material-moment-adapter’;
import {DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE} from ‘@angular/material/core’;
import {MatDatepicker} from ‘@angular/material/datepicker’;

// Depending on whether rollup is used, moment needs to be imported differently.
// Since Moment.js doesn't have a default export, we normally need to import using the `* as`
// syntax. However, rollup creates a synthetic default module and we thus need to import it using
// the `default as` syntax.
import * as _moment from 'moment';
// tslint:disable-next-line:no-duplicate-imports
import {default as _rollupMoment, Moment} from 'moment';

const moment = _rollupMoment || _moment;

// See the Moment.js docs for the meaning of these formats:
// https://momentjs.com/docs/#/displaying/format/
export const MY_FORMATS = {
  parse: {
    dateInput: 'MM/YYYY',
  },
  display: {
    dateInput: 'MM/YYYY',
    monthYearLabel: 'MMM YYYY',
    dateA11yLabel: 'LL',
    monthYearA11yLabel: 'MMMM YYYY',
  },
};

/** @title Datepicker emulating a Year and month picker */
@Component({
selector: ‘datepicker-views-selection-example’,
templateUrl: ‘datepicker-views-selection-example.html’,
styleUrls: [‘datepicker-views-selection-example.css’],
providers: [
// MomentDateAdapter can be automatically provided by importing MomentDateModule in your
// application’s root module. We provide it at the component level here, due to limitations of
// our example generation script.
{
provide: DateAdapter,
useClass: MomentDateAdapter,
deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS]
},

    {provide: MAT_DATE_FORMATS, useValue: MY_FORMATS},
  ],
})
export class DatepickerViewsSelectionExample {
  date = new FormControl(moment());

chosenYearHandler(normalizedYear: Moment) {
const ctrlValue = this.date.value;
ctrlValue.year(normalizedYear.year());
this.date.setValue(ctrlValue);
}

chosenMonthHandler(normalizedMonth: Moment, datepicker: MatDatepicker) {
const ctrlValue = this.date.value;
ctrlValue.month(normalizedMonth.month());
this.date.setValue(ctrlValue);
datepicker.close();
}
}

115
Q

mat-datepicker Setting the selected date

A

The type of values that the datepicker expects depends on the type of DateAdapter provided in your application. The NativeDateAdapter, for example, works directly with plain JavaScript Date objects. When using the MomentDateAdapter, however, the values will all be Moment.js instances. This use of the adapter pattern allows the datepicker component to work with any arbitrary date representation with a custom DateAdapter. See Choosing a date implementation for more information.

Depending on the DateAdapter being used, the datepicker may automatically deserialize certain date formats for you as well. For example, both the NativeDateAdapter and MomentDateAdapter allow ISO 8601 strings to be passed to the datepicker and automatically converted to the proper object type. This can be convenient when binding data directly from your backend to the datepicker. However, the datepicker will not accept date strings formatted in user format such as “1/2/2017” as this is ambiguous and will mean different things depending on the locale of the browser running the code.

As with other types of , the datepicker works with @angular/forms directives such as formGroup, formControl, ngModel, etc.

HTML:

Angular forms

Angular forms (w/ deserialization)

Value binding

TS:
import {Component} from ‘@angular/core’;
import {FormControl} from ‘@angular/forms’;

/** @title Datepicker selected value */
@Component({
  selector: 'datepicker-value-example',
  templateUrl: 'datepicker-value-example.html',
  styleUrls: ['datepicker-value-example.css'],
})
export class DatepickerValueExample {
  date = new FormControl(new Date());
  serializedDate = new FormControl((new Date()).toISOString());
}

mat-form-field {
margin-right: 12px;
}

116
Q

mat-form-field style class

A

mat-form-field {
margin-right: 12px;
}

you need not apply this attribute on mat-form-field, it is applied by default

117
Q

mat-datepicker Changing the datepicker colors

A

The datepicker popup will automatically inherit the color palette (primary, accent, or warn) from the mat-form-field it is attached to. If you would like to specify a different palette for the popup you can do so by setting the color property on mat-datepicker.

TS:
import {Component} from ‘@angular/core’;

/** @title Datepicker palette colors */
@Component({
selector: ‘datepicker-color-example’,
templateUrl: ‘datepicker-color-example.html’,
styleUrls: [‘datepicker-color-example.css’],
})
export class DatepickerColorExample {}

Inherited calendar color

Custom calendar color

118
Q

mat-datepicker Date validation min and max dates

A

There are three properties that add date validation to the datepicker input. The first two are the min and max properties. In addition to enforcing validation on the input, these properties will disable all dates on the calendar popup before or after the respective values and prevent the user from advancing the calendar past the month or year (depending on current view) containing the min or max date.

TS:
import {Component} from ‘@angular/core’;

/** @title Datepicker with min & max validation */
@Component({
selector: ‘datepicker-min-max-example’,
templateUrl: ‘datepicker-min-max-example.html’,
styleUrls: [‘datepicker-min-max-example.css’],
})
export class DatepickerMinMaxExample {
minDate: Date;
maxDate: Date;

  constructor() {
    // Set the minimum to January 1st 20 years in the past and December 31st a year in the future.
    const currentYear = new Date().getFullYear();
    this.minDate = new Date(currentYear - 20, 0, 1);
    this.maxDate = new Date(currentYear + 1, 11, 31);
  }
}

Choose a date

119
Q

mat-datepicker matDatepickerFilter property of the datepicker input

A

The second way to add date validation is using the matDatepickerFilter property of the datepicker input. This property accepts a function of => boolean (where is the date type used by the datepicker, see Choosing a date implementation). A result of true indicates that the date is valid and a result of false indicates that it is not. Again this will also disable the dates on the calendar that are invalid. However, one important difference between using matDatepickerFilter vs using min or max is that filtering out all dates before or after a certain point, will not prevent the user from advancing the calendar past that point.

HTML:

Choose a date

TS:
import {Component} from ‘@angular/core’;

/** @title Datepicker with filter validation */
@Component({
  selector: 'datepicker-filter-example',
  templateUrl: 'datepicker-filter-example.html',
  styleUrls: ['datepicker-filter-example.css'],
})
export class DatepickerFilterExample {
  myFilter = (d: Date | null): boolean => {
    const day = (d || new Date()).getDay();
    // Prevent Saturday and Sunday from being selected.
    return day !== 0 &amp;&amp; day !== 6;
  }
}
120
Q

mat-datepicker matDatepickerFilter property of the datepicker input example

A

for allowing to select only dates after today

TS:
import {Component} from ‘@angular/core’;

/** @title Datepicker with filter validation */
@Component({
  selector: 'datepicker-filter-example',
  templateUrl: 'datepicker-filter-example.html',
  styleUrls: ['datepicker-filter-example.css'],
})
export class DatepickerFilterExample {
  myFilter = (d: Date): boolean => {
    const day = (d || new Date()).getDay();
    // Prevent Saturday and Sunday from being selected.
    return (d.getTime()> new Date().getTime());
  }
}

HTML:

Choose a date

121
Q

mat-datepicker errors

A

In this example the user can back past 2005, but all of the dates before then will be unselectable. They will not be able to go further back in the calendar than 2000. If they manually type in a date that is before the min, after the max, or filtered out, the input will have validation errors.

Each validation property has a different error that can be checked:

A value that violates the min property will have a matDatepickerMin error.
A value that violates the max property will have a matDatepickerMax error.
A value that violates the matDatepickerFilter property will have a matDatepickerFilter error.

122
Q

mat-datepicker Input and change events

A

The input’s native (input) and (change) events will only trigger due to user interaction with the input element; they will not fire when the user selects a date from the calendar popup. Therefore, the datepicker input also has support for (dateInput) and (dateChange) events. These trigger when the user interacts with either the input or the popup.

The (dateInput) event will fire whenever the value changes due to the user typing or selecting a date from the calendar. The (dateChange) event will fire whenever the user finishes typing input (on blur), or when the user chooses a date from the calendar.

TS:
import {Component} from ‘@angular/core’;
import {MatDatepickerInputEvent} from ‘@angular/material/datepicker’;

/** @title Datepicker input and change events */
@Component({
selector: ‘datepicker-events-example’,
templateUrl: ‘datepicker-events-example.html’,
styleUrls: [‘datepicker-events-example.css’],
})
export class DatepickerEventsExample {
events: string[] = [];

addEvent(type: string, event: MatDatepickerInputEvent) {
this.events.push(${type}: ${event.value});
}
}

HTML:

Input & change events

<div>
<div>{{e}}</div>
</div>

CSS:
.example-events {
  height: 200px;
  border: 1px solid #555;
  overflow: auto;
}
123
Q

ngFor - this gets called for every change to the proper it is assigned

A

<div>
<div>{{e}}</div>
</div>

i think that is is the reason to use TrackBy for performance

124
Q

mat-datepicker Disabling parts of the datepicker

A

As with any standard , it is possible to disable the datepicker input by adding the disabled property. By default, the and will inherit their disabled state from the , but this can be overridden by setting the disabled property on the datepicker or toggle elements. This can be useful if you want to disable text input but allow selection via the calendar or vice-versa.

HTML:

<p>

Completely disabled

</p>

<p>

Popup disabled

</p>

<p>

Input disabled

</p>

TS:
import {Component} from ‘@angular/core’;

/** @title Disabled datepicker */
@Component({
selector: ‘datepicker-disabled-example’,
templateUrl: ‘datepicker-disabled-example.html’,
styleUrls: [‘datepicker-disabled-example.css’],
})
export class DatepickerDisabledExample {}

125
Q

mat-datepicker -Touch UI mode

A

The datepicker normally opens as a popup under the input. However this is not ideal for touch devices that don’t have as much screen real estate and need bigger click targets. For this reason has a touchUi property that can be set to true in order to enable a more touch friendly UI where the calendar opens in a large dialog.

HTML:

Choose a date

TS:
import {Component} from ‘@angular/core’;

/** @title Datepicker touch UI */
@Component({
selector: ‘datepicker-touch-example’,
templateUrl: ‘datepicker-touch-example.html’,
styleUrls: [‘datepicker-touch-example.css’],
})
export class DatepickerTouchExample {}

126
Q

mat-datepicker Manually opening and closing the calendar

A

The calendar popup can be programmatically controlled using the open and close methods on the . It also has an opened property that reflects the status of the popup.

HTML:

Open

TS:
import {Component} from ‘@angular/core’;

/** @title Datepicker open method */
@Component({
selector: ‘datepicker-api-example’,
templateUrl: ‘datepicker-api-example.html’,
styleUrls: [‘datepicker-api-example.css’],
})
export class DatepickerApiExample {}

127
Q

mat-datepicker Internationalization

A

Internationalization of the datepicker is configured via four aspects:

The date locale.
The date implementation that the datepicker accepts.
The display and parse formats used by the datepicker.
The message strings used in the datepicker’s UI.

128
Q

mat-datepicker Internationalization Setting the locale code

A

By default, the MAT_DATE_LOCALE injection token will use the existing LOCALE_ID locale code from @angular/core. If you want to override it, you can provide a new value for the MAT_DATE_LOCALE token:

@NgModule({
  providers: [
    {provide: MAT_DATE_LOCALE, useValue: 'en-GB'},
  ],
})
export class MyApp {}

It’s also possible to set the locale at runtime using the setLocale method of the DateAdapter.

HTML:

Different locale

Dynamically switch to French

TS:
import {Component} from '@angular/core';
import {
  MAT_MOMENT_DATE_FORMATS,
  MomentDateAdapter,
  MAT_MOMENT_DATE_ADAPTER_OPTIONS,
} from '@angular/material-moment-adapter';
import {DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE} from '@angular/material/core';

/** @title Datepicker with different locale */
@Component({
selector: ‘datepicker-locale-example’,
templateUrl: ‘datepicker-locale-example.html’,
styleUrls: [‘datepicker-locale-example.css’],
providers: [
// The locale would typically be provided on the root module of your application. We do it at
// the component level here, due to limitations of our example generation script.
{provide: MAT_DATE_LOCALE, useValue: ‘ja-JP’},

// `MomentDateAdapter` and `MAT_MOMENT_DATE_FORMATS` can be automatically provided by importing
// `MatMomentDateModule` in your applications root module. We provide it at the component level
// here, due to limitations of our example generation script.
{
  provide: DateAdapter,
  useClass: MomentDateAdapter,
  deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS]
},
{provide: MAT_DATE_FORMATS, useValue: MAT_MOMENT_DATE_FORMATS},   ], }) export class DatepickerLocaleExample {   constructor(private _adapter: DateAdapter) {}

french() {
this._adapter.setLocale(‘fr’);
}
}

129
Q

Providers at component level

A

we could set providers at the module level or component level

@Component({
selector: ‘datepicker-locale-example’,
templateUrl: ‘datepicker-locale-example.html’,
styleUrls: [‘datepicker-locale-example.css’],
providers: [
// The locale would typically be provided on the root module of your application. We do it at
// the component level here, due to limitations of our example generation script.
{provide: MAT_DATE_LOCALE, useValue: ‘ja-JP’},

// `MomentDateAdapter` and `MAT_MOMENT_DATE_FORMATS` can be automatically provided by importing
// `MatMomentDateModule` in your applications root module. We provide it at the component level
// here, due to limitations of our example generation script.
{
  provide: DateAdapter,
  useClass: MomentDateAdapter,
  deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS]
},
{provide: MAT_DATE_FORMATS, useValue: MAT_MOMENT_DATE_FORMATS},   ], })
--Module level
@NgModule({
  providers: [
    {provide: MAT_DATE_LOCALE, useValue: 'en-GB'},
  ],
})
export class MyApp {}
130
Q

mat-datepicker Internationalization - Choosing a date implementation and date format settings

A

The datepicker was built to be date implementation agnostic. This means that it can be made to work with a variety of different date implementations. However it also means that developers need to make sure to provide the appropriate pieces for the datepicker to work with their chosen implementation.

The easiest way to ensure this is to import one of the provided date modules:

MatNativeDateModule

Date type	Date
Supported locales	en-US
Dependencies	None
Import from	@angular/material/core
MatMomentDateModule

Date type Moment
Supported locales See project
Dependencies Moment.js
Import from @angular/material-moment-adapter
Please note: MatNativeDateModule is based off the functionality available in JavaScript’s native Date object. Thus it is not suitable for many locales. One of the biggest shortcomings of the native Date object is the inability to set the parse format. We highly recommend using the MomentDateAdapter or a custom DateAdapter that works with the formatting/parsing library of your choice.

These modules include providers for DateAdapter and MAT_DATE_FORMATS.

@NgModule({
  imports: [MatDatepickerModule, MatNativeDateModule],
})
export class MyApp {}
Because DateAdapter is a generic class, MatDatepicker and MatDatepickerInput also need to be made generic. When working with these classes (for example as a ViewChild) you should include the appropriate generic type that corresponds to the DateAdapter implementation you are using. For example:
@Component({...})
export class MyComponent {
  @ViewChild(MatDatepicker) datepicker: MatDatepicker;
}
131
Q

Datepicker that uses Moment.js dates example

A

import {Component} from ‘@angular/core’;
import {FormControl} from ‘@angular/forms’;
import {MAT_MOMENT_DATE_FORMATS, MomentDateAdapter} from ‘@angular/material-moment-adapter’;
import {DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE} from ‘@angular/material/core’;

// Depending on whether rollup is used, moment needs to be imported differently.
// Since Moment.js doesn't have a default export, we normally need to import using the `* as`
// syntax. However, rollup creates a synthetic default module and we thus need to import it using
// the `default as` syntax.
import * as _moment from 'moment';
// tslint:disable-next-line:no-duplicate-imports
import {default as _rollupMoment} from 'moment';

const moment = _rollupMoment || _moment;

/** @title Datepicker that uses Moment.js dates */
@Component({
  selector: 'datepicker-moment-example',
  templateUrl: 'datepicker-moment-example.html',
  styleUrls: ['datepicker-moment-example.css'],
  providers: [
    // `MomentDateAdapter` and `MAT_MOMENT_DATE_FORMATS` can be automatically provided by importing
    // `MatMomentDateModule` in your applications root module. We provide it at the component level
    // here, due to limitations of our example generation script.
    {provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE]},
    {provide: MAT_DATE_FORMATS, useValue: MAT_MOMENT_DATE_FORMATS},
  ],
})
export class DatepickerMomentExample {
  // Datepicker takes `Moment` objects instead of `Date` objects.
  date = new FormControl(moment([2017, 0, 1]));
}

HTML:

Moment.js datepicker

132
Q

MomentDateAdapter

A

By default the MomentDateAdapter will creates dates in your time zone specific locale. You can change the default behaviour to parse dates as UTC by providing the MAT_MOMENT_DATE_ADAPTER_OPTIONS and setting it to useUtc: true.

@NgModule({
imports: [MatDatepickerModule, MatMomentDateModule],
providers: [
{provide: MAT_MOMENT_DATE_ADAPTER_OPTIONS, useValue: {useUtc: true}}
]
})
By default the MomentDateAdapter will parse dates in a forgiving way. This may result in dates being parsed incorrectly. You can change the default behaviour to parse dates strictly by providing the MAT_MOMENT_DATE_ADAPTER_OPTIONS and setting it to strict: true.

@NgModule({
imports: [MatDatepickerModule, MatMomentDateModule],
providers: [
{provide: MAT_MOMENT_DATE_ADAPTER_OPTIONS, useValue: {strict: true}}
]
})
It is also possible to create your own DateAdapter that works with any date format your app requires. This is accomplished by subclassing DateAdapter and providing your subclass as the DateAdapter implementation. You will also want to make sure that the MAT_DATE_FORMATS provided in your app are formats that can be understood by your date implementation. See Customizing the parse and display formatsfor more information about MAT_DATE_FORMATS.

@NgModule({
  imports: [MatDatepickerModule],
  providers: [
    {provide: DateAdapter, useClass: MyDateAdapter},
    {provide: MAT_DATE_FORMATS, useValue: MY_DATE_FORMATS},
  ],
})
export class MyApp {}
133
Q
A

is a container component that wraps and formats a series of line items. As the base list component, it provides Material Design styling, but no behavior of its own.

HTML:

Item 1
Item 2
Item 3
element contains a number of elements.

Pepper
Salt
Paprika

134
Q

Navigation lists mat-nav-list ;matLine

A

Use mat-nav-list tags for navigation lists (i.e. lists that have anchor tags).

Simple navigation lists can use the mat-list-item attribute on anchor tag elements directly:

<a> {{ link }} </a>

For more complex navigation lists (e.g. with more than one target per item), wrap the anchor element in an .

 <a href="...">{{ link }}</a>

    info
135
Q

mat-action-list

A

Action lists
Use the element when each item in the list performs some action. Each item in an action list is a element.

Simple action lists can use the mat-list-item attribute on button tag elements directly:

Save
Undo

136
Q

Selection lists - mat-selection-list - like checkbox list

A

A selection list provides an interface for selecting values, where each list item is an option.

HTML:

{{shoe}}

<p>
Options selected: {{shoes.selectedOptions.selected.length}}
</p>

TS:
import {Component} from ‘@angular/core’;

/**
 * @title List with selection
 */
@Component({
  selector: 'list-selection-example',
  styleUrls: ['list-selection-example.css'],
  templateUrl: 'list-selection-example.html',
})
export class ListSelectionExample {
  typesOfShoes: string[] = ['Boots', 'Clogs', 'Loafers', 'Moccasins', 'Sneakers'];
}
137
Q

accessing a template reference in the html of angular app using #, it can also be assesed via @viewchild in component.ts

A

{{shoe}}

<p>
Options selected: {{shoes.selectedOptions.selected.length}}
</p>

The options within a selection-list should not contain further interactive controls, such as buttons and anchors.

138
Q

Multi-line lists mat-line for line in angular

A

For lists that require multiple lines per item, annotate each line with an matLine attribute. Whichever heading tag is appropriate for your DOM hierarchy should be used (not necessarily <h3> as shown in the example).

    <h3> {{message.from}} </h3>
    <p>
      <span> {{message.subject}} </span>
      <span class="demo-2"> -- {{message.content}} </span>
    </p>
<h3> {{message.from}} </h3>
<p> {{message.subject}} </p>
<p class="demo-2"> {{message.content}} </p>

</h3>

139
Q

Lists with icons - i might use this in workbooks page

A

To add an icon to your list item, use the matListIcon attribute.

    folder
    <h3> {{message.from}} </h3>
    <p>
      <span> {{message.subject}} </span>
      <span class="demo-2"> -- {{message.content}} </span>
    </p>
140
Q

Lists with avatars

A

To include an avatar image, add an image tag with an matListAvatar attribute.

    <img>
    <h3> {{message.from}} </h3>
    <p>
      <span> {{message.subject}} </span>
      <span class="demo-2"> -- {{message.content}} </span>
    </p>
141
Q

Dense lists

A

Lists are also available in “dense layout” mode, which shrinks the font size and height of the list to suit UIs that may need to display more information. To enable this mode, add a dense attribute to the main mat-list tag.

Pepper
Salt
Paprika

142
Q

Lists with multiple sections

A

Subheader can be added to a list by annotating a heading tag with an matSubheader attribute. To add a divider, use .

<h3>Folders</h3>

  folder
  <h4>{{folder.name}}</h4>
  <p class="demo-2"> {{folder.updated}} </p>

<h3>Notes</h3>

  note
  <h4>{{note.name}}</h4>
  <p class="demo-2"> {{note.updated}} </p>
143
Q

matSubheader

A

<h3>Folders</h3>

  folder
  <h4>{{folder.name}}</h4>
  <p class="demo-2"> {{folder.updated}} </p>

<h3>Notes</h3>

  note
  <h4>{{note.name}}</h4>
  <p class="demo-2"> {{note.updated}} </p>
144
Q

mat-divider

A

To add a divider, use .

<h3>Folders</h3>

  folder
  <h4>{{folder.name}}</h4>
  <p class="demo-2"> {{folder.updated}} </p>

<h3>Notes</h3>

  note
  <h4>{{note.name}}</h4>
  <p class="demo-2"> {{note.updated}} </p>
145
Q

role attribute on the html and material components

A

Item 1
Item 2
Item 3

Most of the roles you see were defined as part of ARIA 1.0, and then later incorporated into HTML5. Some of the new HTML5 elements (dialog, main, etc.) are even based on the original ARIA roles.

http://www.w3.org/TR/wai-aria/

There are two primary reasons to use roles in addition to your native semantic element.

Reason #1. Overriding the role where no host language element is appropriate or, for various reasons, a less semantically appropriate element was used.

In this example, a link was used, even though the resulting functionality is more button-like than a navigation link.

<a>Delete</a>
Screen readers will hear this as a button (as opposed to a link), and you can use a CSS attribute selector to avoid class-itis and div-itis.

*[role="button"] {
  /* style these a buttons w/o relying on a .button class */
}
Reason #2. Backing up a native element's role, to support browsers that implemented the ARIA role but haven't yet implemented the native element's role.

For example, the “main” role has been supported in browsers for many years, but it’s a relatively recent addition to HTML5, so many browsers don’t yet support the semantic for .


This is technically redundant, but helps some users and doesn’t harm any. In a few years, this technique will likely become unnecessary.

You also wrote:

I see some people make up their own. Is that allowed or a correct use of the role attribute?

That’s a valid use of the attribute unless a real role is not included. Browsers will apply the first recognized role in the token list.

<span>…
Out of the list, only link and note are valid roles, and so the link role will be applied because it comes first. If you use custom roles, make sure they don’t conflict with any defined role in ARIA or the host language you’re using (HTML, SVG, MathML, etc.)</span>

146
Q

mat-button-toggle

A

are on/off toggles with the appearance of a button. These toggles can be configured to behave as either radio-buttons or checkboxes. While they can be standalone, they are typically part of a mat-button-toggle-group.

Bold
Italic
Underline

147
Q

mat-button-toggle Exclusive selection vs. multiple selection

A

By default, mat-button-toggle-group acts like a radio-button group- only one item can be selected. In this mode, the value of the mat-button-toggle-group will reflect the value of the selected button and ngModel is supported.

Adding the multiple attribute allows multiple items to be selected (checkbox behavior). In this mode the values of the toggles are not used, the mat-button-toggle-group does not have a value, and ngModel is not supported.

148
Q

mat-button-toggle Appearance

A

By default, the appearance of mat-button-toggle-group and mat-button-toggle will follow the latest Material Design guidelines. If you want to, you can switch back to the appearance that was following the previous Material Design spec by using the appearance input. The appearance can be configured globally using the MAT_BUTTON_TOGGLE_DEFAULT_OPTIONS injection token.

HTML:

<p>
Default appearance:

Bold
Italic
Underline

</p>

<p>
Legacy appearance:

Bold
Italic
Underline

</p>

TS:
import {Component} from ‘@angular/core’;

/**
* @title Button toggle appearance
*/
@Component({
selector: ‘button-toggle-appearance-example’,
templateUrl: ‘button-toggle-appearance-example.html’,
styleUrls: [‘button-toggle-appearance-example.css’],
})
export class ButtonToggleAppearanceExample {}

149
Q

injection tokens for material components

A

By default, the appearance of mat-button-toggle-group and mat-button-toggle will follow the latest Material Design guidelines. If you want to, you can switch back to the appearance that was following the previous Material Design spec by using the appearance input. The appearance can be configured globally using the MAT_BUTTON_TOGGLE_DEFAULT_OPTIONS injection token.

150
Q

mat-button-toggle

A

The button-toggles can be rendered in a vertical orientation by adding the vertical attribute.

151
Q

button

A

Angular Material buttons are native or <a> elements enhanced with Material Design styling and ink ripples.</a>

Click me!

Native and <a> elements are always used in order to provide the most straightforward and accessible experience for users. A element should be used whenever some action is performed. An <a> element should be used whenever the user will navigate to another view.</a></a>

There are several button variants, each applied as an attribute:

Attribute Description
mat-button Rectangular text button w/ no elevation
mat-raised-button Rectangular contained button w/ elevation
mat-flat-button Rectangular contained button w/ no elevation
mat-stroked-button Rectangular outlined button w/ no elevation
mat-icon-button Circular button with a transparent background, meant to contain an icon
mat-fab Circular button w/ elevation, defaults to theme’s accent color
mat-mini-fab Same as mat-fab but smaller

Theming
Buttons can be colored in terms of the current theme using the color property to set the background color to primary, accent, or warn.

Capitalization
According to the Material design spec button text has to be capitalized, however we have opted not to capitalize buttons automatically via text-transform: uppercase, because it can cause issues in certain locales. It is also worth noting that using ALL CAPS in the text itself causes issues for screen-readers, which will read the text character-by-character. We leave the decision of how to approach this to the consuming app.
</a></a></a>

152
Q

mat-button

A
<h3>Basic Buttons</h3>
<div class="example-button-row">
  Basic
  Primary
  Accent
  Warn
  Disabled
  <a>Link</a>
</div>
153
Q

mat-raised-button

A
<h3>Raised Buttons</h3>
<div class="example-button-row">
  Basic
  Primary
  Accent
  Warn
  Disabled
  <a>Link</a>
</div>
154
Q

mat-stroked-button

A
<h3>Stroked Buttons</h3>
<div class="example-button-row">
  Basic
  Primary
  Accent
  Warn
  Disabled
  <a>Link</a>
</div>
155
Q

mat-flat-button

A
<h3>Flat Buttons</h3>
<div class="example-button-row">
  Basic
  Primary
  Accent
  Warn
  Disabled
  <a>Link</a>
</div>
156
Q

mat-icon-button

A

<h3>Icon Buttons</h3>

<div>

favorite

favorite

favorite

favorite

favorite

</div>

157
Q

mat-fab and mat-mini-fab round buttons

A
<h3>Fab Buttons</h3>
<div class="example-button-row">
  Basic
  Primary
  Accent
  Warn
  Disabled
favorite

<a>Link</a>
</div>

<h3>Mini Fab Buttons</h3>
<div class="example-button-row">
  Basic
  Primary
  Accent
  Warn
  Disabled
favorite

<a>Link</a>
</div>

158
Q

mat-checkbox

A

provides the same functionality as a native enhanced with Material Design styling and animations.

Check me!

159
Q

Checkbox label and support of angular/forms

A

The checkbox label is provided as the content to the element. The label can be positioned before or after the checkbox by setting the labelPosition property to ‘before’ or ‘after’.

If you don’t want the label to appear next to the checkbox, you can use aria-label or aria-labelledby to specify an appropriate label.

Use with @angular/forms
is compatible with @angular/forms and supports both FormsModule and ReactiveFormsModule.

160
Q

mat-checkbox Indeterminate state

A

Indeterminate state
supports an indeterminate state, similar to the native . While the indeterminate property of the checkbox is true, it will render as indeterminate regardless of the checked value. Any interaction with the checkbox by a user (i.e., clicking) will remove the indeterminate state.

Click action config
When user clicks on the mat-checkbox, the default behavior is toggle checked value and set indeterminate to false. This behavior can be customized by providing a new value of MAT_CHECKBOX_CLICK_ACTION to the checkbox.

providers: [
{provide: MAT_CHECKBOX_CLICK_ACTION, useValue: ‘check’}
]
The possible values are:

noop
Do not change the checked value or indeterminate value. Developers have the power to implement customized click actions.

check
Toggle checked value of the checkbox, ignore indeterminate value. If the checkbox is in indeterminate state, the checkbox will display as an indeterminate checkbox regardless the checked value.

check-indeterminate
Default behavior of mat-checkbox. Always set indeterminate to false when user click on the mat-checkbox. This matches the behavior of native .

Theming
The color of a can be changed by using the color property. By default, checkboxes use the theme’s accent color. This can be changed to ‘primary’ or ‘warn’.

161
Q

matSort and mat-sort-header on html table

A

The matSort and mat-sort-header are used, respectively, to add sorting state and display to tabular data.

    Dessert (100g)
    Calories
    Fat (g)
    Carbs (g)
    Protein (g)
    {{dessert.name}}
    {{dessert.calories}}
    {{dessert.fat}}
    {{dessert.carbs}}
    {{dessert.protein}}

import {Component} from ‘@angular/core’;
import {Sort} from ‘@angular/material/sort’;

export interface Dessert {
  calories: number;
  carbs: number;
  fat: number;
  name: string;
  protein: number;
}

/**
* @title Sorting overview
*/
@Component({
selector: ‘sort-overview-example’,
templateUrl: ‘sort-overview-example.html’,
styleUrls: [‘sort-overview-example.css’],
})
export class SortOverviewExample {
desserts: Dessert[] = [
{name: ‘Frozen yogurt’, calories: 159, fat: 6, carbs: 24, protein: 4},
{name: ‘Ice cream sandwich’, calories: 237, fat: 9, carbs: 37, protein: 4},
{name: ‘Eclair’, calories: 262, fat: 16, carbs: 24, protein: 6},
{name: ‘Cupcake’, calories: 305, fat: 4, carbs: 67, protein: 4},
{name: ‘Gingerbread’, calories: 356, fat: 16, carbs: 49, protein: 4},
];

sortedData: Dessert[];

constructor() {
this.sortedData = this.desserts.slice();
}

  sortData(sort: Sort) {
    const data = this.desserts.slice();
    if (!sort.active || sort.direction === '') {
      this.sortedData = data;
      return;
    }
    this.sortedData = data.sort((a, b) => {
      const isAsc = sort.direction === 'asc';
      switch (sort.active) {
        case 'name': return compare(a.name, b.name, isAsc);
        case 'calories': return compare(a.calories, b.calories, isAsc);
        case 'fat': return compare(a.fat, b.fat, isAsc);
        case 'carbs': return compare(a.carbs, b.carbs, isAsc);
        case 'protein': return compare(a.protein, b.protein, isAsc);
        default: return 0;
      }
    });
  }
}
function compare(a: number | string, b: number | string, isAsc: boolean) {
  return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
}
162
Q

fxFlexOffset

A

The fxFlexOffset directive should be used on on elements within a fxLayout container and dictates the margin between elements

<div>
  <div>1. One</div>
  <div>2. Two</div>
  <div>3. Three</div>
  <div>4. Four</div>
</div>
163
Q

Theme in angular material - to set color

A

in angular.json
under styles section; we define the themes
we might use default angular themes like deeppurple-amber.css which has deep purple as primary and amber(yellow) as accent color

we could find the prebuilt themes in
node_modules/@angular/material/prebuilt-themes

164
Q

mat-core

A

@import ‘~angular/material/theming’
it offers some functions in scss to use to create a new theme

@include mat-core()- it gives lot of base styling for angular material packages

165
Q

What is a theme?

A

https://material.angular.io/guide/theming

Angular Material’s theming system enables you to customize components to better reflect your product’s brand. A theme consists of configurations for the individual color and typography systems in Angular Material. The library’s approach to theming reflects the guidance from the Material Design spec.

In Angular Material, you create a color configuration by composing multiple palettes. In particular, a color configuration consists of:

A primary palette: colors most widely used across all screens and components.
An accent palette: colors used for the floating action button and interactive elements.
A warn palette: colors used to convey error state.
A foreground palette: colors for text and icons.
A background palette: colors used for element backgrounds.
Additionally, in Angular Material, a configuration may optionally include typography settings. More information on how typography works can be found in a dedicated guide.

Angular Material theme styles are generated statically at build-time so that your app doesn’t have to spend cycles generating theme styles on startup.

166
Q

Using a pre-built theme

A

Angular Material comes prepackaged with several pre-built theme css files. These theme files also include all of the styles for core (styles common to all components), so you only have to include a single css file for Angular Material in your app.

You can include a theme file directly into your application from @angular/material/prebuilt-themes

Available pre-built themes:

deeppurple-amber.css
indigo-pink.css
pink-bluegrey.css
purple-green.css
If you're using Angular CLI, this is as simple as including one line in your styles.css file:

@import ‘@angular/material/prebuilt-themes/deeppurple-amber.css’;
Alternatively, you can just reference the file directly. This would look something like:

The actual path will depend on your server setup.

You can also concatenate the file with the rest of your application’s css.

Finally, if your app’s content is not placed inside of a mat-sidenav-container element, you need to add the mat-app-background class to your wrapper element (for example the body). This ensures that the proper theme background is applied to your page.

167
Q

Defining a custom theme

A

When you want more customization than a pre-built theme offers, you can create your own theme file.

A custom theme file does two things:

Imports the mat-core() Sass mixin. This includes all common styles that are used by multiple components. This should only be included once in your application. If this mixin is included multiple times, your application will end up with multiple copies of these common styles.
Defines a theme data structure as the composition of configurations for the individual theming systems (color and typography). This object can be created with either the mat-light-theme function or the mat-dark-theme function. The output of this function is then passed to the angular-material-theme mixin, which will output all of the corresponding styles for the theme.
A typical theme file will look something like this:

@import '~@angular/material/theming';
// Plus imports for other components in your app.
// Include the common styles for Angular Material. We include this here so that you only
// have to load a single css file for Angular Material in your app.
// Be sure that you only ever include this mixin once!
@include mat-core();

// Define the palettes for your theme using the Material Design palettes available in palette.scss
// (imported above). For each palette, you can optionally specify a default, lighter, and darker
// hue. Available color palettes: https://material.io/design/color/
$candy-app-primary: mat-palette($mat-indigo);
$candy-app-accent: mat-palette($mat-pink, A200, A100, A400);

// The warn palette is optional (defaults to red).
$candy-app-warn:    mat-palette($mat-red);
// Create the theme object. A theme consists of configurations for individual
// theming systems such as `color` or `typography`.
$candy-app-theme: mat-light-theme((
  color: (
    primary: $candy-app-primary,
    accent: $candy-app-accent,
    warn: $candy-app-warn,  
  )
));
// Include theme styles for core and each component used in your app.
// Alternatively, you can import and @include the theme mixins for each component
// that you are using.
@include angular-material-theme($candy-app-theme);
You only need this single Sass file; you do not need to use Sass to style the rest of your app.

If you are using the Angular CLI, support for compiling Sass to css is built-in; you only have to add a new entry to the “styles” list in angular.json pointing to the theme file (e.g., unicorn-app-theme.scss).

If you’re not using the Angular CLI, you can use any existing Sass tooling to build the file (such as gulp-sass or grunt-sass). The simplest approach is to use the node-sass CLI; you simply run:

node-sass src/unicorn-app-theme.scss dist/unicorn-app-theme.css
and then include the output file in your index.html.

Your custom theme file should not be imported into other SCSS files. This will duplicate styles in your CSS output. If you want to consume your theme definition object (e.g., $candy-app-theme) in other SCSS files, then the definition of the theme object should be broken into its own file, separate from the inclusion of the mat-core and angular-material-theme mixins.

The theme file can be concatenated and minified with the rest of the application’s css.

Note that if you include the generated theme file in the styleUrls of an Angular component, those styles will be subject to that component’s view encapsulation.

168
Q

Multiple themes

A

You can create multiple themes for your application by including the angular-material-theme mixin multiple times, where each inclusion is gated by an additional CSS class.

Remember to only ever include the @mat-core mixin once; it should not be included for each theme.

Example of defining multiple themes:
@import '~@angular/material/theming';
// Plus imports for other components in your app.
// Include the common styles for Angular Material. We include this here so that you only
// have to load a single css file for Angular Material in your app.
// **Be sure that you only ever include this mixin once!**
@include mat-core();

// Define the default theme (same as the example above).
$candy-app-primary: mat-palette($mat-indigo);
$candy-app-accent: mat-palette($mat-pink, A200, A100, A400);
$candy-app-theme: mat-light-theme((
color: (
primary: $candy-app-primary,
accent: $candy-app-accent,
)
));

// Include the default theme styles (color and default density)
@include angular-material-theme($candy-app-theme);

// Define an alternate dark theme.
$dark-primary: mat-palette($mat-blue-grey);
$dark-accent: mat-palette($mat-amber, A200, A100, A400);
$dark-warn: mat-palette($mat-deep-orange);
$dark-theme: mat-dark-theme((
color: (
primary: $dark-primary,
accent: $dark-accent,
warn: $dark-warn,
)
));

// Include the dark color styles inside of a block with a CSS class. You can make this
// CSS class whatever you want. In this example, any component inside of an element with
// `.unicorn-dark-theme` will be affected by this alternate dark theme instead of the default theme.
.unicorn-dark-theme {
  @include angular-material-color($dark-theme);
}
In the above example, any component inside of a parent with the unicorn-dark-theme class will use the dark theme, while other components will fall back to the default $candy-app-theme.

You can include as many color schemes as you like in this manner. You can also @include the angular-material-color in separate files and then lazily load them based on an end-user interaction (how to lazily load the CSS assets will vary based on your application).

It’s important to remember, however, that the mat-core mixin should only ever be included once. Similarly, the angular-material-theme mixin should not be used multiple times as it generates styles for all configured theming system parts. For example, typography styles would be generated multiple times, even though the configuration did not change. Instead, use fine-grained mixins such as angular-material-color that only result in styles being generated for the color system.

Read more about duplicated theme styles in the dedicated guide.

169
Q

Multiple themes and overlay-based components

A

Since certain components (e.g. menu, select, dialog, etc.) are inside of a global overlay container, an additional step is required for those components to be affected by the theme’s css class selector (.unicorn-dark-theme in the example above).

To do this, you can add the appropriate class to the global overlay container. For the example above, this would look like:

import {OverlayContainer} from ‘@angular/cdk/overlay’;

@NgModule({
  // ...
})
export class UnicornCandyAppModule {
  constructor(overlayContainer: OverlayContainer) {
    overlayContainer.getContainerElement().classList.add('unicorn-dark-theme');
  }
}
170
Q

Theming only certain components

A

The angular-material-theme mixin will output styles for all components in the library. If you are only using a subset of the components (or if you want to change the theme for specific components), you can include component-specific theme mixins. You also will need to include the mat-core-theme mixin as well, which contains theme-specific styles for common behaviors (such as ripples).

@import '~@angular/material/theming';
// Plus imports for other components in your app.
// Include the common styles for Angular Material. We include this here so that you only
// have to load a single css file for Angular Material in your app.
// **Be sure that you only ever include this mixin once!**
@include mat-core();
// Define the theme.
$candy-app-primary: mat-palette($mat-indigo);
$candy-app-accent:  mat-palette($mat-pink, A200, A100, A400);
$candy-app-theme:   mat-light-theme((
  color: (
    primary: $candy-app-primary,
    accent: $candy-app-accent,
  )
));

// Include the theme styles for only specified components.
@include mat-core-theme($candy-app-theme);
@include mat-button-theme($candy-app-theme);
@include mat-checkbox-theme($candy-app-theme);

171
Q

Changing styles at run-time

A
Toggling classes
You can use the theming mixins to customize any part of your application with standard CSS selectors. For example, let's say you want to toggle alternate colors on a button. You would first define a CSS class with the alternate colors.

Note that mat-button-color should be used instead of mat-button-theme as we only want to have alternate colors for the button. Using the theme mixin could result in duplicative theme styles if the mat-button-theme has been included before. Read more about this in the dedicated guide.

.alternate-button {
  // Extract the color configuration from the theme and generate
  // the color theme styles for `mat-button`.
  @include mat-button-color($alternate-theme);
}
Then you can use normal Angular class bindings to toggle the alternate styles.

<div>
Save changes
</div>

You can use this approach to style any component inside of the region marked with the custom CSS class.

172
Q

Swapping CSS files

A

If you want to completely swap a theme without including all of the styles at once, you can swap the loaded theme file. The details will depend on your application, but the general idea looks like this:

function changeTheme(themeName) {
  document.getElementById('themeAsset').href = `/path/to/my/${themeName}.css`;
}
173
Q

What is typography?

A

https://material.angular.io/guide/typography

Typography is a way of arranging type to make text legible, readable, and appealing when displayed. Angular Material’s typography is based on the guidelines from the Material Design spec and is arranged into typography levels. Each level has a font-size, line-height and font-weight. The available levels are:

Name CSS classes Description
display-4 .mat-display-4 Large, one-off header, usually at the top of the page (e.g. a hero header).
display-3 .mat-display-3 Large, one-off header, usually at the top of the page (e.g. a hero header).
display-2 .mat-display-2 Large, one-off header, usually at the top of the page (e.g. a hero header).
display-1 .mat-display-1 Large, one-off header, usually at the top of the page (e.g. a hero header).
headline .mat-h1, .mat-headline Section heading corresponding to the <h1> tag.
title .mat-h2, .mat-title Section heading corresponding to the <h2> tag.
subheading-2 .mat-h3, .mat-subheading-2 Section heading corresponding to the <h3> tag.
subheading-1 .mat-h4, .mat-subheading-1 Section heading corresponding to the <h4> tag.
body-1 .mat-body, .mat-body-1 Base body text.
body-2 .mat-body-strong, .mat-body-2 Bolder body text.
caption .mat-small, .mat-caption Smaller body and hint text.
button None. Used only in components. Buttons and anchors.
input None. Used only in components. Form input fields.
The typography levels are collected into a typography config which is used to generate the CSS.

Usage
To get started, you first include the Roboto font with the 300, 400 and 500 weights. You can host it yourself or include it from Google Fonts:

Now you can add the appropriate CSS classes to the elements that you want to style:

<h1 class="mat-display-1">Jackdaws love my big sphinx of quartz.</h1>
<h2 class="mat-h2">The quick brown fox jumps over the lazy dog.</h2>
By default, Angular Material doesn't apply any global CSS. To apply the library's typographic styles more broadly, you can take advantage of the mat-typography CSS class. This class will style all descendant native elements.

<h1>This header is unstyled</h1>

<h1>This header will be styled</h1>

</h4></h3></h2></h1>

174
Q

Customization of typography

A

Typography customization is an extension of Angular Material’s Sass-based theming. Similar to creating a custom theme, you can create a custom typography configuration.

@import ‘~@angular/material/theming’;

// Define a custom typography config that overrides the font-family as well as the
// headlines and body-1 levels.
$custom-typography: mat-typography-config(
$font-family: ‘Roboto, monospace’,
$headline: mat-typography-level(32px, 48px, 700),
$body-1: mat-typography-level(16px, 24px, 500)
);
As the above example demonstrates, a typography configuration is created by using the mat-typography-config function, which is given both the font-family and the set of typographic levels described earlier. Each typographic level is defined by the mat-typography-level function, which requires a font-size, line-height, and font-weight. Note that the font-family has to be in quotes.

Once the custom typography definition is created, it can be consumed to generate styles via different Sass mixins.

// Override typography CSS classes (e.g., mat-h1, mat-display-1, mat-typography, etc.).
@include mat-base-typography($custom-typography);
// Override typography for a specific Angular Material components.
@include mat-checkbox-typography($custom-typography);
// Override typography for all Angular Material, including mat-base-typography and all components.
@include angular-material-typography($custom-typography);
If you're using Material's theming, you can also pass in your typography config to the mat-core mixin:
// Override the typography in the core CSS.
@include mat-core($custom-typography);
For more details about the typography functions and default config, see the source.
175
Q

Material typography in your custom CSS

A

Angular Material includes typography utility mixins and functions that you can use to customize your own components:

mat-font-size($config, $level) - Gets the font-size, based on the provided config and level.
mat-font-family($config) - Gets the font-family, based on the provided config.
mat-line-height($config, $level) - Gets the line-height, based on the provided config and level.
mat-font-weight($config, $level) - Gets the font-weight, based on the provided config and level.
mat-typography-level-to-styles($config, $level) - Mixin that takes in a configuration object and a typography level, and outputs a short-hand CSS font declaration.
@import ‘~@angular/material/theming’;

// Create a config with the default typography levels.
$config: mat-typography-config();

// Custom header that uses only the Material font-size and font-family.
.unicorn-header {
font-size: mat-font-size($config, headline);
font-family: mat-font-family($config);
}

// Custom title that uses all of the typography styles from the `title` level.
.unicorn-title {
  @include mat-typography-level-to-styles($config, title);
}
176
Q

HOW TO: set up angular theme in your project

A

create customtheme.scss ; may be add it to assets folder
this theme file should have the primary,accent warn colors defined and call mat-light-thme mixing with these parameters
then call the angular-material-theme mixin

// Define the palettes for your theme using the Material Design palettes available in palette.scss
// (imported above). For each palette, you can optionally specify a default, lighter, and darker
// hue. Available color palettes: https://www.google.com/design/spec/style/color.html
$chmc-primary: mat-palette($chmc-teal);
$chmc-accent: mat-palette($chmc-purple);

// The warn palette is optional (defaults to red).
$chmc-warn:    mat-palette($mat-red);
// Create the theme object (a Sass map containing all of the palettes).
$chmc-theme: mat-light-theme($chmc-primary, $chmc-accent, $chmc-warn);
// Include theme styles for core and each component used in your app.
// Alternatively, you can import and @include the theme mixins for each component
// that you are using.
@include angular-material-theme($chmc-theme);

in the angular.json we need to add this asset file under styles section

“styles”: [

          "src/assets/CCHMC-theme.scss",
          "src/styles.scss"
        ], NOTE: then we need add the angular/material to the project; we will see the next steps later
177
Q

complete CCHMC theme file

A
/* You can add global styles to this file, and also import other style files */
@import '~@angular/material/theming';
// Plus imports for other components in your app.
@import 'chmc';
@import url('//fonts.googleapis.com/icon?family=Material+Icons');
// Include the common styles for Angular Material. We include this here so that you only
// have to load a single css file for Angular Material in your app.
// Be sure that you only ever include this mixin once!
@include mat-core();

$chmc-san-serif-font: Arial;
$chmc-serif-font: Georgia;

$chmc-teal: (
    50 : #e0f5f8,
    100 : #b3e7ee,
    200 : #80d7e3,
    300 : #4dc6d8,
    400 : #26bacf,
    500 : #00aec7,
    600 : #00a7c1,
    700 : #009dba,
    800 : #0094b3,
    900 : #0084a6,
    A100 : #d0f4ff,
    A200 : #9de8ff,
    A400 : #6adbff,
    A700 : #51d5ff,
    contrast: (
        50 : $dark-primary-text,
        100 : $dark-primary-text,
        200 : $dark-primary-text,
        300 : $dark-primary-text,
        400 : $dark-primary-text,
        500 : $light-primary-text,
        600 : $light-primary-text,
        700 : $light-primary-text,
        800 : $light-primary-text,
        900 : $light-primary-text,
        A100 : $dark-primary-text,
        A200 : $dark-primary-text,
        A400 : $dark-primary-text,
        A700 : $dark-primary-text,
    )
);
$chmc-purple: (
    50 : #f8ebf3,
    100 : #eecde1,
    200 : #e3abcd,
    300 : #d789b8,
    400 : #cf70a9,
    500 : #c6579a,
    600 : #c04f92,
    700 : #b94688,
    800 : #b13c7e,
    900 : #a42c6c,
    A100 : #ffe7f3,
    A200 : #ffb4db,
    A400 : #ff81c2,
    A700 : #ff68b6,
    contrast: (
        50 : $dark-primary-text,
        100 : $dark-primary-text,
        200 : $dark-primary-text,
        300 : $dark-primary-text,
        400 : $dark-primary-text,
        500 : $light-primary-text,
        600 : $light-primary-text,
        700 : $light-primary-text,
        800 : $light-primary-text,
        900 : $light-primary-text,
        A100 : $dark-primary-text,
        A200 : $dark-primary-text,
        A400 : $dark-primary-text,
        A700 : $dark-primary-text,
    )
);
$chmc-green: (
    50 : #eff7e4,
    100 : #d7ecbc,
    200 : #bcdf90,
    300 : #a1d263,
    400 : #8cc841,
    500 : #78be20,
    600 : #70b81c,
    700 : #65af18,
    800 : #5ba713,
    900 : #48990b,
    A100 : #ddffc8,
    A200 : #bdff95,
    A400 : #9dff62,
    A700 : #8eff48,
    contrast: (
        50 : $dark-primary-text,
        100 : $dark-primary-text,
        200 : $dark-primary-text,
        300 : $dark-primary-text,
        400 : $dark-primary-text,
        500 : $dark-primary-text,
        600 : $dark-primary-text,
        700 : $dark-primary-text,
        800 : $light-primary-text,
        900 : $light-primary-text,
        A100 : $dark-primary-text,
        A200 : $dark-primary-text,
        A400 : $dark-primary-text,
        A700 : $dark-primary-text,
    )
);
$chmc-gray: (
    50 : #eaebeb,
    100 : #cccdce,
    200 : #aaacad,
    300 : #878a8c,
    400 : #6e7173,
    500 : #54585a,
    600 : #4d5052,
    700 : #434748,
    800 : #3a3d3f,
    900 : #292d2e,
    A100 : #86daf7,
    A200 : #57ccf3,
    A400 : #18c5ff,
    A700 : #00befd,
    contrast: (
        50 : $dark-primary-text,
        100 : $dark-primary-text,
        200 : $dark-primary-text,
        300 : $dark-primary-text,
        400 : $light-primary-text,
        500 : $light-primary-text,
        600 : $light-primary-text,
        700 : $light-primary-text,
        800 : $light-primary-text,
        900 : $light-primary-text,
        A100 : $dark-primary-text,
        A200 : $dark-primary-text,
        A400 : $dark-primary-text,
        A700 : $dark-primary-text,
    )
);
$chmc-light-green: (
    50 : #f4fae7,
    100 : #e4f2c2,
    200 : #d2e999,
    300 : #bfe070,
    400 : #b2d952,
    500 : #a4d233,
    600 : #9ccd2e,
    700 : #92c727,
    800 : #89c120,
    900 : #78b614,
    A100 : #f5ffe7,
    A200 : #e0ffb4,
    A400 : #cbff81,
    A700 : #c0ff68,
    contrast: (
        50 : $dark-primary-text,
        100 : $dark-primary-text,
        200 : $dark-primary-text,
        300 : $dark-primary-text,
        400 : $dark-primary-text,
        500 : $dark-primary-text,
        600 : $dark-primary-text,
        700 : $dark-primary-text,
        800 : $dark-primary-text,
        900 : $dark-primary-text,
        A100 : $dark-primary-text,
        A200 : $dark-primary-text,
        A400 : $dark-primary-text,
        A700 : $dark-primary-text,
    )
);
$chmc-light-blue: (
    50 : #f3fafb,
    100 : #e1f2f5,
    200 : #cde9ee,
    300 : #b9e0e7,
    400 : #aadae2,
    500 : #9bd3dd,
    600 : #93ced9,
    700 : #89c8d4,
    800 : #7fc2cf,
    900 : #6db7c7,
    A100 : $light-primary-text,
    A200 : $light-primary-text,
    A400 : #d9f8ff,
    A700 : #bff4ff,
    contrast: (
        50 : $dark-primary-text,
        100 : $dark-primary-text,
        200 : $dark-primary-text,
        300 : $dark-primary-text,
        400 : $dark-primary-text,
        500 : $dark-primary-text,
        600 : $dark-primary-text,
        700 : $dark-primary-text,
        800 : $dark-primary-text,
        900 : $dark-primary-text,
        A100 : $dark-primary-text,
        A200 : $dark-primary-text,
        A400 : $dark-primary-text,
        A700 : $dark-primary-text,
    )
);
$chmc-medium-blue: (
    50 : #eef8fc,
    100 : #d4eef8,
    200 : #b8e2f4,
    300 : #9cd6ef,
    400 : #86ceeb,
    500 : #71c5e8,
    600 : #69bfe5,
    700 : #5eb8e2,
    800 : #54b0de,
    900 : #42a3d8,
    A100 : $light-primary-text,
    A200 : #f7fcff,
    A400 : #c4eaff,
    A700 : #abe0ff,
    contrast: (
        50 : $dark-primary-text,
        100 : $dark-primary-text,
        200 : $dark-primary-text,
        300 : $dark-primary-text,
        400 : $dark-primary-text,
        500 : $dark-primary-text,
        600 : $dark-primary-text,
        700 : $dark-primary-text,
        800 : $dark-primary-text,
        900 : $dark-primary-text,
        A100 : $dark-primary-text,
        A200 : $dark-primary-text,
        A400 : $dark-primary-text,
        A700 : $dark-primary-text,
    )
);
$chmc-pink: (
    50 : #fbe9ef,
    100 : #f6c7d7,
    200 : #f0a2bd,
    300 : #e97da3,
    400 : #e5618f,
    500 : #e0457b,
    600 : #dc3e73,
    700 : #d83668,
    800 : #d32e5e,
    900 : #cb1f4b,
    A100 : $light-primary-text,
    A200 : #ffcfda,
    A400 : #ff9cb3,
    A700 : #ff839f,
    contrast: (
        50 : $dark-primary-text,
        100 : $dark-primary-text,
        200 : $dark-primary-text,
        300 : $dark-primary-text,
        400 : $dark-primary-text,
        500 : $light-primary-text,
        600 : $light-primary-text,
        700 : $light-primary-text,
        800 : $light-primary-text,
        900 : $light-primary-text,
        A100 : $dark-primary-text,
        A200 : $dark-primary-text,
        A400 : $dark-primary-text,
        A700 : $dark-primary-text,
    )
);
$chmc-medium-purple: (
    50 : #f3e9ef,
    100 : #e0c8d7,
    200 : #cca4bc,
    300 : #b87fa1,
    400 : #a8638c,
    500 : #994878,
    600 : #914170,
    700 : #863865,
    800 : #7c305b,
    900 : #6b2148,
    A100 : #ffabd5,
    A200 : #ff78bc,
    A400 : #ff45a3,
    A700 : #ff2b97,
    contrast: (
        50 : $dark-primary-text,
        100 : $dark-primary-text,
        200 : $dark-primary-text,
        300 : $dark-primary-text,
        400 : $light-primary-text,
        500 : $light-primary-text,
        600 : $light-primary-text,
        700 : $light-primary-text,
        800 : $light-primary-text,
        900 : $light-primary-text,
        A100 : $dark-primary-text,
        A200 : $dark-primary-text,
        A400 : $dark-primary-text,
        A700 : $light-primary-text,
    )
);
$chmc-dark-purple: (
    50 : #f0e5ed,
    100 : #d9bed3,
    200 : #c093b6,
    300 : #a66898,
    400 : #934782,
    500 : #80276c,
    600 : #782364,
    700 : #6d1d59,
    800 : #63174f,
    900 : #500e3d,
    A100 : #ff87d8,
    A200 : #ff54c8,
    A400 : #ff21b8,
    A700 : #ff08af,
    contrast: (
        50 : $dark-primary-text,
        100 : $dark-primary-text,
        200 : $dark-primary-text,
        300 : $dark-primary-text,
        400 : $light-primary-text,
        500 : $light-primary-text,
        600 : $light-primary-text,
        700 : $light-primary-text,
        800 : $light-primary-text,
        900 : $light-primary-text,
        A100 : $dark-primary-text,
        A200 : $dark-primary-text,
        A400 : $light-primary-text,
        A700 : $light-primary-text,
    )
);

// Define the palettes for your theme using the Material Design palettes available in palette.scss
// (imported above). For each palette, you can optionally specify a default, lighter, and darker
// hue. Available color palettes: https://www.google.com/design/spec/style/color.html
$chmc-primary: mat-palette($chmc-teal);
$chmc-accent: mat-palette($chmc-purple);

// The warn palette is optional (defaults to red).
$chmc-warn:    mat-palette($mat-red);
// Create the theme object (a Sass map containing all of the palettes).
$chmc-theme: mat-light-theme($chmc-primary, $chmc-accent, $chmc-warn);
// Include theme styles for core and each component used in your app.
// Alternatively, you can import and @include the theme mixins for each component
// that you are using.
@include angular-material-theme($chmc-theme);

body{
font-family: $chmc-san-serif-font
}

178
Q

How to: add angular/material to the project

A

Install Angular Material
Use the Angular CLI’s install schematic to set up your Angular Material project by running the following command:

ng add @angular/material

The ng add command will install Angular Material, the Component Dev Kit (CDK), Angular Animations and ask you the following questions to determine which features to include:

this will add these to the package.json:
“dependencies”: {
“@angular/cdk”: “~10.2.3-sha-8b4ce730a”,
“@angular/material”: “~10.2.3-sha-8b4ce730a”
}

Choose a prebuilt theme name, or “custom” for a custom theme:
if we choose custom theme then the primary, accent and warn will be generated in styles.css with the project name as prefix
you could either use them with your colors or create a separate theme file and use them

You can choose from prebuilt material design themes or set up an extensible custom theme.

Set up browser animations for Angular Material:

Importing the BrowserAnimationsModule into your application enables Angular’s animation system. Declining this will disable most of Angular Material’s animations.
this did not create any new entries into package.json; may be they are already exisits
“@angular/platform-browser”: “~10.0.6”,
“@angular/platform-browser-dynamic”: “~10.0.6”,

but lines are added to appModule.ts:
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
 imports: [
     BrowserAnimationsModule  
  ]

The ng add command will additionally perform the following configurations:

Add project dependencies to package.json
Add the Roboto font to your index.html
Add the Material Design icon font to your index.html
in index.html:

Add a few global CSS styles to:

Remove margins from body
Set height: 100% on html and body
Set Roboto as the default application font
in styles.scss:
html, body { height: 100%; }
body { margin: 0; font-family: Roboto, “Helvetica Neue”, sans-serif; }

in index.html:

You’re done! Angular Material is now configured to be used in your application.

179
Q

How to: Import multile material components

A

https://material.angular.io/guide/getting-started

add material.module.ts in the app/shared folder
Note: we can not import all the components in one-go from @angular/material; we need to import them one by one

import { NgModule } from ‘@angular/core’;
import { MatAutocompleteModule } from ‘@angular/material/Autocomplete’;
import { MatButtonModule } from ‘@angular/material/Button’;

@NgModule({
  imports: [
    CdkTableModule,
    MatAutocompleteModule,
    MatButtonModule
]
,
  exports: [
    CdkTableModule,
    MatAutocompleteModule,
    MatButtonModule,
],
})
export class MaterialModule {}
in app.module.ts: import this module
import { MaterialModule } from './shared/material.module';
 imports: [
    MaterialModule
  ],
using in component:
<h1>
  OPPE Data submission Portal !!
</h1>
Primary
Accent

Components can no longer be imported through “@angular/material”. Use the individual secondary entry-points, such as @angular/material/button.

Update: can confirm, this was the issue. After downgrading @angular/material@9.0… to @angular/material@7.3.2 we could solve this temporarily. Guess we need to update the project for a long term solution.

180
Q

angular cdk

A

111

https://material.angular.io/cdk/categories

CDK is the short form of component dev kit. This signifies that these are general-purpose tools for building components that are not coupled to Material Design

From the material2 changelog

Several components in core/, such as Overlay, have had their prefix changed to cdk- (short for “component dev kit”). This signifies that these are general-purpose tools for building components that are not coupled to Material Design.The old selectors are still available as deprecated but will be removed in the next release. The CSS classes have been changed.
For more info on how to use cdk components such as table, overlay, portal, portal host, e.t.c, you can find examples here:

https: //github.com/angular/material2/tree/master/src/demo-app
https: //medium.com/@caroso1222/a-first-look-into-the-angular-cdk-67e68807ed9b

181
Q

complete list of angular material components imported in material module

A

import { NgModule } from ‘@angular/core’;
import { MatAutocompleteModule } from ‘@angular/material/Autocomplete’;
import { MatButtonModule } from ‘@angular/material/Button’;
import { MatButtonToggleModule } from ‘@angular/material/button-toggle’;
import { MatCardModule } from ‘@angular/material/Card’;
import { MatCheckboxModule } from ‘@angular/material/Checkbox’;
import { MatChipsModule } from ‘@angular/material/Chips’;
import { MatDatepickerModule } from ‘@angular/material/Datepicker’;
import { MatDialogModule } from ‘@angular/material/Dialog’;
import { MatDividerModule } from ‘@angular/material/Divider’;
import { MatExpansionModule } from ‘@angular/material/Expansion’;
import { MatGridListModule } from ‘@angular/material/Grid-List’;
import { MatIconModule } from ‘@angular/material/Icon’;
import { MatInputModule } from ‘@angular/material/Input’;
import { MatListModule } from ‘@angular/material/List’;
import { MatMenuModule } from ‘@angular/material/Menu’;
import { MatPaginatorModule } from ‘@angular/material/Paginator’;
import { MatProgressBarModule } from ‘@angular/material/Progress-Bar’;
import { MatProgressSpinnerModule } from ‘@angular/material/Progress-Spinner’;
import { MatRadioModule } from ‘@angular/material/Radio’;
import { MatRippleModule } from ‘@angular/material/core’;
import { MatSelectModule } from ‘@angular/material/Select’;
import { MatSidenavModule } from ‘@angular/material/Sidenav’;
import { MatSliderModule } from ‘@angular/material/Slider’;
import { MatSlideToggleModule } from ‘@angular/material/Slide-Toggle’;
import { MatSnackBarModule } from ‘@angular/material/Snack-Bar’;
import { MatSortModule } from ‘@angular/material/Sort’;
import { MatStepperModule } from ‘@angular/material/Stepper’;
import { MatTableModule } from ‘@angular/material/Table’;
import { MatTabsModule } from ‘@angular/material/Tabs’;
import { MatToolbarModule } from ‘@angular/material/Toolbar’;
import { MatTooltipModule } from ‘@angular/material/Tooltip’;
import { CdkTableModule } from ‘@angular/cdk/table’;

@NgModule({
  imports: [
    CdkTableModule,
    MatAutocompleteModule,
    MatButtonModule,
    MatButtonToggleModule,
    MatCardModule,
    MatCheckboxModule,
    MatChipsModule,
    MatStepperModule,
    MatDatepickerModule,
    MatDialogModule,
    MatDividerModule,
    MatExpansionModule,
    MatGridListModule,
    MatIconModule,
    MatInputModule,
    MatListModule,
    MatMenuModule,
    MatPaginatorModule,
    MatProgressBarModule,
    MatProgressSpinnerModule,
    MatRadioModule,
    MatRippleModule,
    MatSelectModule,
    MatSidenavModule,
    MatSliderModule,
    MatSlideToggleModule,
    MatSnackBarModule,
    MatSortModule,
    MatTableModule,
    MatTabsModule,
    MatToolbarModule,
    MatTooltipModule,
  ],
  exports: [
    CdkTableModule,
    MatAutocompleteModule,
    MatButtonModule,
    MatButtonToggleModule,
    MatCardModule,
    MatCheckboxModule,
    MatChipsModule,
    MatStepperModule,
    MatDatepickerModule,
    MatDialogModule,
    MatDividerModule,
    MatExpansionModule,
    MatGridListModule,
    MatIconModule,
    MatInputModule,
    MatListModule,
    MatMenuModule,
    MatPaginatorModule,
    MatProgressBarModule,
    MatProgressSpinnerModule,
    MatRadioModule,
    MatRippleModule,
    MatSelectModule,
    MatSidenavModule,
    MatSliderModule,
    MatSlideToggleModule,
    MatSnackBarModule,
    MatSortModule,
    MatTableModule,
    MatTabsModule,
    MatToolbarModule,
    MatTooltipModule,
  ],
})
export class MaterialModule {}
182
Q

Multiple themes

A

It’s important to remember, however, that the mat-core mixin should only ever be included once. Similarly, the angular-material-theme mixin should not be used multiple times as it generates styles for all configured theming system parts. For example, typography styles would be generated multiple times, even though the configuration did not change. Instead, use fine-grained mixins such as angular-material-color that only result in styles being generated for the color system.

You can create multiple themes for your application by including the angular-material-theme mixin multiple times, where each inclusion is gated by an additional CSS class.

Remember to only ever include the @mat-core mixin once; it should not be included for each theme.

Example of defining multiple themes:
@import '~@angular/material/theming';
// Plus imports for other components in your app.
// Include the common styles for Angular Material. We include this here so that you only
// have to load a single css file for Angular Material in your app.
// **Be sure that you only ever include this mixin once!**
@include mat-core();

// Define the default theme (same as the example above).
$candy-app-primary: mat-palette($mat-indigo);
$candy-app-accent: mat-palette($mat-pink, A200, A100, A400);
$candy-app-theme: mat-light-theme((
color: (
primary: $candy-app-primary,
accent: $candy-app-accent,
)
));

// Include the default theme styles (color and default density)
@include angular-material-theme($candy-app-theme);

// Define an alternate dark theme.
$dark-primary: mat-palette($mat-blue-grey);
$dark-accent: mat-palette($mat-amber, A200, A100, A400);
$dark-warn: mat-palette($mat-deep-orange);
$dark-theme: mat-dark-theme((
color: (
primary: $dark-primary,
accent: $dark-accent,
warn: $dark-warn,
)
));

// Include the dark color styles inside of a block with a CSS class. You can make this
// CSS class whatever you want. In this example, any component inside of an element with
// `.unicorn-dark-theme` will be affected by this alternate dark theme instead of the default theme.
.unicorn-dark-theme {
  @include angular-material-color($dark-theme);
}
In the above example, any component inside of a parent with the unicorn-dark-theme class will use the dark theme, while other components will fall back to the default $candy-app-theme.

You can include as many color schemes as you like in this manner. You can also @include the angular-material-color in separate files and then lazily load them based on an end-user interaction (how to lazily load the CSS assets will vary based on your application).

It’s important to remember, however, that the mat-core mixin should only ever be included once. Similarly, the angular-material-theme mixin should not be used multiple times as it generates styles for all configured theming system parts. For example, typography styles would be generated multiple times, even though the configuration did not change. Instead, use fine-grained mixins such as angular-material-color that only result in styles being generated for the color system.

Read more about duplicated theme styles in the dedicated guide.

183
Q

Multiple themes and overlay-based components

A

https://material.angular.io/guide/theming

Since certain components (e.g. menu, select, dialog, etc.) are inside of a global overlay container, an additional step is required for those components to be affected by the theme’s css class selector (.unicorn-dark-theme in the example above).

To do this, you can add the appropriate class to the global overlay container. For the example above, this would look like:

import {OverlayContainer} from ‘@angular/cdk/overlay’;

@NgModule({
  // ...
})
export class UnicornCandyAppModule {
  constructor(overlayContainer: OverlayContainer) {
    overlayContainer.getContainerElement().classList.add('unicorn-dark-theme');
  }
}
184
Q

Theming only certain components

A

The angular-material-theme mixin will output styles for all components in the library. If you are only using a subset of the components (or if you want to change the theme for specific components), you can include component-specific theme mixins. You also will need to include the mat-core-theme mixin as well, which contains theme-specific styles for common behaviors (such as ripples).

@import '~@angular/material/theming';
// Plus imports for other components in your app.
// Include the common styles for Angular Material. We include this here so that you only
// have to load a single css file for Angular Material in your app.
// **Be sure that you only ever include this mixin once!**
@include mat-core();
// Define the theme.
$candy-app-primary: mat-palette($mat-indigo);
$candy-app-accent:  mat-palette($mat-pink, A200, A100, A400);
$candy-app-theme:   mat-light-theme((
  color: (
    primary: $candy-app-primary,
    accent: $candy-app-accent,
  )
));

// Include the theme styles for only specified components.
@include mat-core-theme($candy-app-theme);
@include mat-button-theme($candy-app-theme);
@include mat-checkbox-theme($candy-app-theme);

185
Q

Changing styles at run-time

Toggling classes

A

You can use the theming mixins to customize any part of your application with standard CSS selectors. For example, let’s say you want to toggle alternate colors on a button. You would first define a CSS class with the alternate colors.

Note that mat-button-color should be used instead of mat-button-theme as we only want to have alternate colors for the button. Using the theme mixin could result in duplicative theme styles if the mat-button-theme has been included before. Read more about this in the dedicated guide.

.alternate-button {
  // Extract the color configuration from the theme and generate
  // the color theme styles for `mat-button`.
  @include mat-button-color($alternate-theme);
}
Then you can use normal Angular class bindings to toggle the alternate styles.

<div>
Save changes
</div>

You can use this approach to style any component inside of the region marked with the custom CSS class.

186
Q

Swapping CSS files

A

If you want to completely swap a theme without including all of the styles at once, you can swap the loaded theme file. The details will depend on your application, but the general idea looks like this:

function changeTheme(themeName) {
  document.getElementById('themeAsset').href = `/path/to/my/${themeName}.css`;
}
187
Q

Display a Material component

A

Let’s display a slider component in your app and verify that everything works.

You need to import the MatSliderModule that you want to display by adding the following lines to your app.module.ts file.

import { MatSliderModule } from '@angular/material/slider';
…
@NgModule ({....
  imports: [...,
  MatSliderModule,
…]
})
Add the  tag to the app.component.html like so:

Run your local dev server:

ng serve
and point your browser to http://localhost:4200

You should see the material slider component on the page.

In addition to the install schematic, Angular Material comes with several schematics (like nav, table, address-form, etc.) that can be used to easily generate pre-built components in your application.

188
Q

Material Schematics

A

Angular Material comes packaged with Angular CLI schematics to make creating Material applications easier.

https://material.angular.io/guide/schematics

Install Schematics
Schematics are included with both @angular/cdk and @angular/material. Once you install the npm packages, they will be available through the Angular CLI.

Using the command below will install Angular Material, the Component Dev Kit (CDK), and Angular Animations in your project. Then it will run the install schematic.

ng add @angular/material
In case you just want to install the @angular/cdk, there are also schematics for the Component Dev Kit

ng add @angular/cdk
The Angular Material ng add schematic helps you setup an Angular CLI project that uses Material. Running ng add will:

Ensure project dependencies are placed in package.json
Enable the BrowserAnimationsModule your app module
Add either a prebuilt theme or a custom theme
Add Roboto fonts to your index.html
Add the Material Icon font to your index.html
Add global styles to
Remove margins from body
Set height: 100% on html and body
Make Roboto the default font of your app
Component schematics
In addition to the install schematic, Angular Material comes with multiple schematics that can be used to easily generate Material Design components:

Name Description
address-form Component with a form group that uses Material Design form controls to prompt for a shipping address
navigation Creates a component with a responsive Material Design sidenav and a toolbar for showing the app name
dashboard Component with multiple Material Design cards and menus which are aligned in a grid layout
table Generates a component with a Material Design data table that supports sorting and pagination
tree Component that interactively visualizes a nested folder structure by using the component
Additionally the Angular CDK also comes with a collection of component schematics:

Name Description
drag-drop Component that uses the @angular/cdk/drag-drop directives for creating an interactive to-do list
Address form schematic
Running the address-form schematic generates a new Angular component that can be used to get started with a Material Design form group consisting of:

Material Design form fields
Material Design radio controls
Material Design buttons
ng generate @angular/material:address-form
Navigation schematic
The navigation schematic will create a new component that includes a toolbar with the app name and a responsive side nav based on Material breakpoints.

ng generate @angular/material:navigation
Table schematic
The table schematic will create a component that renders an Angular Material which has been pre-configured with a datasource for sorting and pagination.

ng generate @angular/material:table
Dashboard schematic
The dashboard schematic will create a new component that contains a dynamic grid list of Material Design cards.

ng generate @angular/material:dashboard
Tree schematic
The tree schematic can be used to quickly generate an Angular component that uses the Angular Material component to visualize a nested folder structure.

ng generate @angular/material:tree
Drag and Drop schematic
The drag-drop schematic is provided by the @angular/cdk and can be used to generate a component that uses the CDK drag and drop directives.

ng generate @angular/cdk:drag-drop

189
Q

Angular stepper

A

https://material.angular.io/components/stepper/overview

190
Q

mat-table -renderRows() method

A

Since the table optimizes for performance, it will not automatically check for changes to the data array. Instead, when objects are added, removed, or moved on the data array, you can trigger an update to the table’s rendered rows by calling its renderRows() method.