<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Angular Material Blog &#8212; onthecode</title>
	<atom:link href="https://onthecode.co.uk/blog/category/angular-material/feed" rel="self" type="application/rss+xml" />
	<link>https://onthecode.co.uk/blog/category/angular-material</link>
	<description>onthecode blog</description>
	<lastBuildDate>Sat, 22 Feb 2025 19:55:11 +0000</lastBuildDate>
	<language>en-GB</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.6.3</generator>

<image>
	<url>https://onthecode.co.uk/wp-content/uploads/2019/02/onthecode-icon-1-100x100.png</url>
	<title>Angular Material Blog &#8212; onthecode</title>
	<link>https://onthecode.co.uk/blog/category/angular-material</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>How to Use Angular Material Theme Colours in Your Components</title>
		<link>https://onthecode.co.uk/blog/how-to-use-angular-material-theme-colours-in-your-components</link>
					<comments>https://onthecode.co.uk/blog/how-to-use-angular-material-theme-colours-in-your-components#respond</comments>
		
		<dc:creator><![CDATA[Umut Esen]]></dc:creator>
		<pubDate>Fri, 17 Jun 2022 09:40:15 +0000</pubDate>
				<category><![CDATA[Angular Material]]></category>
		<guid isPermaLink="false">https://onthecode.co.uk/?p=4668</guid>

					<description><![CDATA[<p>Angular Material comes with pre-built themes to make getting started easy. Once you&#8217;ve picked a theme such as indigo-pink, you may want to re-use the base colours in your own components for consistency. Instead of creating your own scss variables, I would suggest copying base colours from Angular Material. Let&#8217;s copy $primary and $accent colours from Angular Material: Assuming you&#8217;re working on a real project and not a hello-world app, you should consider creating a file to keep these variables. As this is a new file, Angular compiler needs to know about it. Go ahead and add it to the styles array in your angular.json: Finally, you can import the new variables file in any component and use $primary and $accent: So there you have it! This is how I re-use colours from Angular Material to keep things consistent. Do you know any other way to do this? Let me know in the comments below!</p>
<p>The post <a href="https://onthecode.co.uk/blog/how-to-use-angular-material-theme-colours-in-your-components">How to Use Angular Material Theme Colours in Your Components</a> appeared first on <a href="https://onthecode.co.uk">onthecode</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Angular Material comes with pre-built themes to make getting started easy. Once you&#8217;ve picked a theme such as <code>indigo-pink</code>, you may want to re-use the base colours in your own components for consistency. </p>



<p>Instead of creating your own <code>scss</code> variables, I would suggest copying base colours from Angular Material.</p>



<p>Let&#8217;s copy <code>$primary</code> and <code>$accent</code> colours from Angular Material:</p>


<pre class="wp-block-code"><span><code class="hljs language-scss"><span class="hljs-keyword">@import</span> <span class="hljs-string">"~@angular/material/theming"</span>;

<span class="hljs-comment">// Copy colour palettes individually</span>
<span class="hljs-variable">$app-primary</span>: mat-palette(<span class="hljs-variable">$mat-indigo</span>);
<span class="hljs-variable">$app-accent</span>: mat-palette(<span class="hljs-variable">$mat-pink</span>);

<span class="hljs-comment">// Create variables to use in project</span>
<span class="hljs-variable">$primary</span>: mat-color(<span class="hljs-variable">$app-primary</span>);
<span class="hljs-variable">$accent</span>: mat-color(<span class="hljs-variable">$app-accent</span>);</code></span></pre>


<p>Assuming you&#8217;re working on a real project and not a hello-world app, you should consider creating a file to keep these variables.</p>


<pre class="wp-block-code"><span><code class="hljs language-bash">src/assets/_variables.scss</code></span></pre>


<p>As this is a new file, Angular compiler needs to know about it. </p>



<p>Go ahead and add it to the styles array in your <code>angular.json</code>:</p>


<pre class="wp-block-code"><span><code class="hljs language-json shcb-code-table"><span class='shcb-loc'><span><span class="hljs-string">"styles"</span>: &#91; 
</span></span><mark class='shcb-loc'><span>    <span class="hljs-string">"src/assets/_variables.scss"</span>
</span></mark><span class='shcb-loc'><span>]
</span></span></code></span></pre>


<p>Finally, you can import the new variables file in any component and use <code>$primary</code> and <code>$accent</code>:</p>


<pre class="wp-block-code"><span><code class="hljs language-css"><span class="hljs-keyword">@import</span> <span class="hljs-string">"./../../../assets/_variables"</span>;

<span class="hljs-selector-class">.entry</span> {
    <span class="hljs-attribute">background-color</span>: $primary;
}</code></span></pre>


<p>So there you have it! This is how I re-use colours from Angular Material to keep things consistent. </p>



<p>Do you know any other way to do this? Let me know in the comments below!</p>
<p>The post <a href="https://onthecode.co.uk/blog/how-to-use-angular-material-theme-colours-in-your-components">How to Use Angular Material Theme Colours in Your Components</a> appeared first on <a href="https://onthecode.co.uk">onthecode</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://onthecode.co.uk/blog/how-to-use-angular-material-theme-colours-in-your-components/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to Set Focus on Form Control in Angular</title>
		<link>https://onthecode.co.uk/blog/angular-material-focus-form-input-with-renderer2</link>
					<comments>https://onthecode.co.uk/blog/angular-material-focus-form-input-with-renderer2#comments</comments>
		
		<dc:creator><![CDATA[Umut Esen]]></dc:creator>
		<pubDate>Sat, 23 Feb 2019 22:42:11 +0000</pubDate>
				<category><![CDATA[Angular Material]]></category>
		<category><![CDATA[angular best practices]]></category>
		<category><![CDATA[angular focus form input]]></category>
		<category><![CDATA[angular material tutorial]]></category>
		<category><![CDATA[mat-input]]></category>
		<category><![CDATA[npm]]></category>
		<category><![CDATA[renderer2]]></category>
		<category><![CDATA[typescript]]></category>
		<guid isPermaLink="false">https://onthecode.co.uk/?p=1824</guid>

					<description><![CDATA[<p>In this post, I will show you how to programmatically set focus on a form control in Angular. Instead of the popular ElementRef solution, we will use Renderer2 to set focus on a form input. This approach is secure, easier to test and compatible with reactive forms. Here&#8217;s a live demo on how to focus on form input in Angular Material: Using ElementRef First of all, I have seen many Angular examples that involve using ElementRef to get access to the native HTML element and calling focus(). The following is from a recent example I have seen from codeburst. In this approach, you reference the HTML input element with ViewChild in typescript code. ElementRef is included in Angular core library. It is a wrapper around native HTML elements. The variable nameField above refers to a native HTML element, which we can manipulate in code. Security Risks ElementRef in Angular gives direct access to HTML DOM (Document Object Model). Allowing direct access to the DOM can make your application vulnerable to XSS attacks. You should always avoid using ElementRef in Angular where possible. Separation of concerns Relying on ElementRef for HTML DOM operations like form input focus and blur creates tight coupling between the application and rendering layers. So if you wanted use web workers, it will be impossible to separate the application logic from DOM manipulation code. Focusing input with Renderer2 Renderer2 is a service that comes with the core Angular package. It allows DOM manipulation in a safe way. It&#8217;s a bit like jQuery for Angular. Although, I have a reactive form below for demonstration, all you need is an input with a unique id. Inject Renderer 2 in the constructor and access the input element with selectRootElement() method. Then, we can focus on the input using focus method: In addition, you can focus on input element on load, using the ngAfterViewInit() hook. Another useful feature of Renderer2 is that you can listen for events on elements. For example, you can subscribe to the focus and blur events of the input with listen() method. In the code snippet below, we are grabbing the input element and subscribing to focus and blur events. It is important that you setup listeners in ngAfterViewInit() hook as the element won&#8217;t be initialised in ngOnInit(). There you have it! That&#8217;s how to set focus on form control with Renderer2 in Angular.</p>
<p>The post <a href="https://onthecode.co.uk/blog/angular-material-focus-form-input-with-renderer2">How to Set Focus on Form Control in Angular</a> appeared first on <a href="https://onthecode.co.uk">onthecode</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>In this post, I will show you how to programmatically set focus on a form control in <a href="/blog/category/angular" target="_blank" rel="noreferrer noopener">Angular</a>. </p>



<p>Instead of the popular <code>ElementRef</code> solution, we will use <a href="https://angular.io/api/core/Renderer2#description" target="_blank" rel="noreferrer noopener">Renderer2</a> to set focus on a form input. This approach is secure, easier to test and compatible with reactive forms.</p>






<p>Here&#8217;s a live demo on how to focus on form input in Angular Material:</p>



<iframe height="400" src="https://stackblitz.com/edit/angular-focus-input?ctl=1&amp;embed=1&amp;file=app/input-overview-example.ts"></iframe>



<h2 class="wp-block-heading">Using ElementRef</h2>



<p>First of all, I have seen many Angular examples that involve using <a aria-label="ElementRef (opens in a new tab)" href="https://angular.io/api/core/ElementRef" target="_blank" rel="noreferrer noopener">ElementRef</a> to get access to the native HTML element and calling <code>focus()</code>. The following is from a recent example I have seen from <a aria-label="codeburst (opens in a new tab)" href="https://codeburst.io/focusing-on-form-elements-the-angular-way-e9a78725c04f" target="_blank" rel="noreferrer noopener nofollow">codeburst</a>.</p>



<div class="wp-block-image"><figure class="aligncenter is-resized"><img fetchpriority="high" decoding="async" src="https://onthecode.co.uk/wp-content/uploads/2019/02/1_f6YkIf25raG2WH1MFrtttQ.png" alt="" class="wp-image-1848" width="512" height="134" srcset="https://onthecode.co.uk/wp-content/uploads/2019/02/1_f6YkIf25raG2WH1MFrtttQ.png 682w, https://onthecode.co.uk/wp-content/uploads/2019/02/1_f6YkIf25raG2WH1MFrtttQ-300x78.png 300w, https://onthecode.co.uk/wp-content/uploads/2019/02/1_f6YkIf25raG2WH1MFrtttQ-600x157.png 600w" sizes="(max-width: 512px) 100vw, 512px" /><figcaption>Focus on HTML input with ElementRef in Angular</figcaption></figure></div>



<p>In this approach, you reference the HTML input element with <code>ViewChild</code> in typescript code.</p>



<p class="info-block">ElementRef is included in Angular core library. It is a wrapper around native HTML elements.</p>



<p>The variable <code>nameField</code> above refers to a native HTML element, which we can manipulate in code.</p>



<h4 class="wp-block-heading"><strong>Security Risks</strong></h4>



<p>ElementRef in Angular gives direct access to HTML DOM (Document Object Model). Allowing direct access to the DOM can make your application vulnerable to XSS attacks.</p>



<p>You should always avoid using ElementRef in Angular where possible.</p>



<h4 class="wp-block-heading"><strong>Separation of concerns</strong></h4>



<p>Relying on ElementRef for HTML DOM operations like <strong>form input</strong> <strong>focus</strong> and <strong>blur</strong> creates tight coupling between the application and rendering layers. So if you wanted use web workers, it will be impossible to separate the application logic from DOM manipulation code.</p>



<h2 class="wp-block-heading">Focusing input with Renderer2</h2>



<p><a rel="noreferrer noopener" aria-label="Renderer2 (opens in a new tab)" href="https://angular.io/api/core/Renderer2#description" target="_blank">Renderer2</a> is a service that comes with the core Angular package. It allows DOM manipulation in a safe way. </p>



<p>It&#8217;s a bit like jQuery for Angular.</p>



<p>Although, I have a reactive form below for demonstration, all you need is an input with a unique id.</p>


<pre class="wp-block-code"><span><code class="hljs language-xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> &#091;<span class="hljs-attr">formGroup</span>]=<span class="hljs-string">"form"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">mat-form-field</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"full-width"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">matInput</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"myInput"</span> <span class="hljs-attr">formControlName</span>=<span class="hljs-string">"myInput"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Focused Input"</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">mat-form-field</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">br</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">mat-raised-button</span> <span class="hljs-attr">color</span>=<span class="hljs-string">"primary"</span> (<span class="hljs-attr">click</span>)=<span class="hljs-string">"focusMyInput()"</span>&gt;</span>Focus<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span></code></span></pre>


<p>Inject Renderer 2 in the constructor and access the input element with <code>selectRootElement()</code> method. </p>



<p>Then, we can focus on the input using <code>focus</code> method:</p>


<pre class="wp-block-code"><span><code class="hljs language-typescript"><span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> renderer: Renderer2</span>) {}

focusMyInput() {
  <span class="hljs-keyword">this</span>.renderer.selectRootElement(<span class="hljs-string">'#myInput'</span>).focus();
}</code></span></pre>


<p>In addition, you can focus on input element on load, using the <code>ngAfterViewInit()</code> hook.</p>


<pre class="wp-block-code"><span><code class="hljs language-typescript">ngAfterViewInit() {
  setTimeout(<span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> {

      <span class="hljs-keyword">var</span> element = <span class="hljs-keyword">this</span>.renderer.selectRootElement(<span class="hljs-string">'#myInput'</span>);
      element.focus();

  }, <span class="hljs-number">1000</span>);
}</code></span></pre>


<p>Another useful feature of Renderer2 is that you can listen for events on elements. </p>



<p>For example, you can subscribe to the focus and blur events of the input with <code>listen()</code> method. </p>



<p>In the code snippet below, we are grabbing the input element and subscribing to focus and blur events.</p>


<pre class="wp-block-code"><span><code class="hljs language-typescript">ngAfterViewInit() {
  setTimeout(<span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> {
      <span class="hljs-keyword">var</span> elem = <span class="hljs-keyword">this</span>.renderer.selectRootElement(<span class="hljs-string">'#myInput'</span>);

      <span class="hljs-keyword">this</span>.renderer.listen(elem, <span class="hljs-string">"focus"</span>, <span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> { <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'focus'</span>) });

      <span class="hljs-keyword">this</span>.renderer.listen(elem, <span class="hljs-string">"blur"</span>, <span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> { <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'blur'</span>) });
  }, <span class="hljs-number">1000</span>);
}</code></span></pre>


<p>It is important that you setup listeners in <code>ngAfterViewInit()</code> hook as the element won&#8217;t be initialised in <code>ngOnInit()</code>.</p>



<p>There you have it! That&#8217;s how to set focus on form control with Renderer2 in Angular.</p>
<p>The post <a href="https://onthecode.co.uk/blog/angular-material-focus-form-input-with-renderer2">How to Set Focus on Form Control in Angular</a> appeared first on <a href="https://onthecode.co.uk">onthecode</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://onthecode.co.uk/blog/angular-material-focus-form-input-with-renderer2/feed</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>How to Make Angular Material Dialog Draggable with cdkDrag</title>
		<link>https://onthecode.co.uk/blog/how-to-make-angular-material-dialog-draggable-with-cdkdrag</link>
					<comments>https://onthecode.co.uk/blog/how-to-make-angular-material-dialog-draggable-with-cdkdrag#comments</comments>
		
		<dc:creator><![CDATA[Umut Esen]]></dc:creator>
		<pubDate>Mon, 18 Feb 2019 09:00:48 +0000</pubDate>
				<category><![CDATA[Angular Material]]></category>
		<category><![CDATA[angular drag and drop]]></category>
		<category><![CDATA[angular material dialog]]></category>
		<category><![CDATA[cdk]]></category>
		<category><![CDATA[typescript]]></category>
		<guid isPermaLink="false">https://onthecode.co.uk/?p=1701</guid>

					<description><![CDATA[<p>With the Angular Material 7 release, an exciting feature we&#8217;ve been waiting for — drag and drop is available with the component dev kit. In my previous article, I explained how to create a reusable confirm dialog with Angular Material. Today, we’ll learn how to make the dialog draggable. We will use the cdkDrag directive from the Component Dev Kit (CDK). cdkDrag allows us to&#160;easily and declaratively create enable drag-and-drop&#160;functionality on components — no need to write custom directives! Import DragDropModule Let&#8217;s import DragDropModule from the CDK into the module where you want to use drag and drop. Since I am keeping the project structure clean with a custom feature module for Material components, I use the CustomMaterialModule for this. You can learn more about my project structure. Use cdkDrag With the DragDropModule in the project, we&#8217;re ready to get things moving. Modify html template of the dialog to add cdkDrag and cdkDragRootElement&#160; directives. That&#8217;s it! You can now move the dialog around using the title. In most cases, cdkDrag is simply enough to make any div draggable. However, the dialog is injected into the DOM so we need to specifically tell Angular the root element to enable drag. For this reason, we pass cdk-overlay-pane class for cdkDragRootElement attribute because it is the root container of the dialog. Add a drag handle Although the dialog is draggable, it is also not obvious that the dialog can be dragged. Let&#8217;s add an icon on the left hand-side of the title to draw the user&#8217;s attention. Import the MatIconModule so that we can use material icon library. Import Material font icons in index.html file. Add a mat-icon element in the dialog title. This is what the title looks like with a drag handle: Add some styling so that the icon looks nice next to the title: Here is the result: Summary In this article, we have seen how easy it is to make the Angular Material Dialog draggable with cdkDrag directive.</p>
<p>The post <a href="https://onthecode.co.uk/blog/how-to-make-angular-material-dialog-draggable-with-cdkdrag">How to Make Angular Material Dialog Draggable with cdkDrag</a> appeared first on <a href="https://onthecode.co.uk">onthecode</a>.</p>
]]></description>
										<content:encoded><![CDATA[</p>
<p>With the Angular Material 7 release, an exciting feature we&#8217;ve been waiting for — drag and drop is available with the component dev kit. </p>
</p>
<p>In my previous article, I explained how to create a <a href="https://onthecode.co.uk/create-confirm-dialog-angular-material/">reusable confirm dialog</a> with Angular Material. Today, we’ll learn how to make the <a href="https://material.angular.io/components/dialog/overview" target="_blank" rel="noreferrer noopener">dialog</a> draggable. We will use the <code>cdkDrag</code> directive from the Component Dev Kit (CDK). </p>
</p>
<p><code>cdkDrag</code> allows us to&nbsp;easily and declaratively create enable drag-and-drop&nbsp;functionality on components — no need to write custom directives!</p>
</p>
<p>
</p>
</p>
<h2 class="wp-block-heading">Import DragDropModule</h2>
</p>
<p>Let&#8217;s import <code>DragDropModule</code> from the CDK into the module where you want to use drag and drop. Since I am keeping the project structure clean with a custom feature module for Material components, I use the <code>CustomMaterialModule</code> for this. You can learn more about my <a href="https://onthecode.co.uk/import-angular-material-feature-module/" target="_blank" rel="noreferrer noopener">project structure</a>.</p>
</p>
<pre class="wp-block-code"><code>import { NgModule } from '@angular/core';
import { MatButtonModule, MatDialogModule } from '@angular/material';
import { DragDropModule } from '@angular/cdk/drag-drop';

@NgModule({
  imports: &#091;
    MatButtonModule, MatDialogModule, DragDropModule
  ],
  exports: &#091;
    MatButtonModule, MatDialogModule, DragDropModule
  ]
})
export class CustomMaterialModule {
}</code></pre>
</p>
<h2 class="wp-block-heading">Use cdkDrag</h2>
</p>
<p>With the <code>DragDropModule</code> in the project, we&#8217;re ready to get things moving.</p>
</p>
<p>Modify html template of the dialog to add <code>cdkDrag</code> and <code>cdkDragRootElement&nbsp;</code> directives. </p>
</p>
<pre class="wp-block-code"><code>&lt;!-- confirm-dialog.component.html --&gt;

&lt;h1 mat-dialog-title cdkDrag cdkDragRootElement=".cdk-overlay-pane"&gt;
  {{title}}
&lt;/h1&gt;

&lt;!-- rest of the dialog --&gt;</code></pre>
</p>
<div class="wp-block-image">
<figure class="aligncenter"><img decoding="async" width="480" height="240" src="https://onthecode.co.uk/wp-content/uploads/2019/02/draggable-angular-material-dialog.gif" alt="" class="wp-image-1774"/><figcaption>Draggable Material Dialog </figcaption></figure>
</div>
</p>
<p>That&#8217;s it! You can now move the dialog around using the title. </p>
</p>
<p>In most cases, <code>cdkDrag</code> is simply enough to make any div draggable. However, the dialog is injected into the DOM so we need to specifically tell Angular the root element to enable drag. For this reason, we pass <code>cdk-overlay-pane</code> class for <code>cdkDragRootElement</code> attribute because it is the root container of the dialog. </p>
</p>
<h2 class="wp-block-heading">Add a drag handle</h2>
</p>
<p>Although the dialog is draggable, it is also not obvious that the dialog <em>can be </em>dragged. </p>
</p>
<p>Let&#8217;s add an icon on the left hand-side of the title to draw the user&#8217;s attention.</p>
</p>
<ol class="wp-block-list">
<li>Import the <code>MatIconModule</code> so that we can use material icon library.</li>
<li>Import Material font icons in <code>index.html</code> file.</li>
<li>Add a <code>mat-icon</code> element in the dialog title.</li>
</ol>
</p>
<p>This is what the title looks like with a drag handle:</p>
</p>
<pre class="wp-block-code"><code>&lt;h1 mat-dialog-title cdkDrag cdkDragRootElement=".cdk-overlay-pane" cdkDragHandle&gt;
  &lt;mat-icon&gt;drag_handle&lt;/mat-icon&gt;
  {{title}}
&lt;/h1&gt;</code></pre>
</p>
<p>Add some styling so that the icon looks nice next to the title:</p>
</p>
<pre class="wp-block-code"><code>.mat-dialog-title .mat-icon {
    top: 5px;
    position: relative;
    cursor: grab;
}</code></pre>
</p>
<p>Here is the result:</p>
</p>
<div class="wp-block-image">
<figure class="aligncenter is-resized"><img decoding="async" src="https://onthecode.co.uk/wp-content/uploads/2019/02/draggable-dialog-with-icon.png" alt="" class="wp-image-1780" width="355" height="248" srcset="https://onthecode.co.uk/wp-content/uploads/2019/02/draggable-dialog-with-icon.png 744w, https://onthecode.co.uk/wp-content/uploads/2019/02/draggable-dialog-with-icon-300x210.png 300w, https://onthecode.co.uk/wp-content/uploads/2019/02/draggable-dialog-with-icon-700x489.png 700w" sizes="(max-width: 355px) 100vw, 355px" /><figcaption>Drag Handle</figcaption></figure>
</div>
</p>
<h2 class="wp-block-heading">Summary</h2>
</p>
<p>In this article, we have seen how easy it is to make the Angular Material Dialog draggable with <code>cdkDrag</code> directive.</p>
</p>
<div class="wp-block-file aligncenter"><a id="wp-block-file--media-a43adaa6-f6bd-489c-95ef-6be9dd9d08ce" href="https://onthecode.co.uk/wp-content/uploads/2019/09/AngularMaterialConfirmDialog-master.zip">AngularMaterialConfirmDialog-master</a><a href="https://onthecode.co.uk/wp-content/uploads/2019/09/AngularMaterialConfirmDialog-master.zip" class="wp-block-file__button" download aria-describedby="wp-block-file--media-a43adaa6-f6bd-489c-95ef-6be9dd9d08ce">Download final code</a></div>
</p></p>
<p>The post <a href="https://onthecode.co.uk/blog/how-to-make-angular-material-dialog-draggable-with-cdkdrag">How to Make Angular Material Dialog Draggable with cdkDrag</a> appeared first on <a href="https://onthecode.co.uk">onthecode</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://onthecode.co.uk/blog/how-to-make-angular-material-dialog-draggable-with-cdkdrag/feed</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>Select All Option for MatSelect</title>
		<link>https://onthecode.co.uk/blog/select-all-option-mat-select</link>
					<comments>https://onthecode.co.uk/blog/select-all-option-mat-select#comments</comments>
		
		<dc:creator><![CDATA[Umut Esen]]></dc:creator>
		<pubDate>Wed, 13 Feb 2019 13:36:33 +0000</pubDate>
				<category><![CDATA[Angular Material]]></category>
		<category><![CDATA[angular 7]]></category>
		<category><![CDATA[angular material tutorial]]></category>
		<category><![CDATA[mat-select]]></category>
		<category><![CDATA[npm]]></category>
		<category><![CDATA[typescript]]></category>
		<guid isPermaLink="false">https://onthecode.co.uk/?p=1690</guid>

					<description><![CDATA[<p>In this post, you&#8217;ll learn how to implement select all option for mat-select from Angular Material. Our solution will involve creating a custom component that will be embedded inside a select dropdown. It will also support indeterminate mode of checkbox, meaning our new option will show a different icon based on selected options. Why do you need a select all option? Angular Material select component has a multi-select feature, which allows users to check multiple options. Unfortunately, there is no way to display select all option out-of-the-box. I can sometimes be useful to select/deselect all options in mat-select dropdown when there are several options. For example, a user may want to select all Projects in a dropdown. Instead of clicking one by one, they can save time by clicking a single option. Therefore, we can build a re-usable select all option to make our users life easier! Step #1: Create a component for select all option Firstly, let&#8217;s generate a new component to make the select all logic reusable: Then, place a mat-checkbox inside the component template. This is the Select all option. After that, set the CSS class to mat-option so that its styling is consistent with other options in mat-select. Using data-binding, we update the indeterminate and checked state of the checkbox. This is important to show an icon representing the state of the mat-select. Moreover, the checkbox needs to have access to the mat-select. Using reactive forms, we will pass in the form control and the list of values to the checkbox. Let&#8217;s take a look at the component implementation: Notice we use @Input variables to pass the form control, selectable values and display text. Finally, add the following styles so that the checkbox takes up full width. Step #2: Embed custom component in a mat-select At last, we can use the custom component to select all options within a mat-select. Start by creating a form and add a mat-select with multiple selection. Above the loop for generating options, add the app-select-check-all component. This way, our custom component will appear as the first item in the list. Don&#8217;t forget to pass in the form control value and the full list of values into app-select-check-all component. Live demo Here is a stackblitz project demonstrating select all option for mat-select: Summary In conclusion, you learned how to select all options in Angular Material Select with a custom checkbox component. This custom behaviour provides a way for user to quickly select all options. Did you find this useful? Let me know in the comments below!</p>
<p>The post <a href="https://onthecode.co.uk/blog/select-all-option-mat-select">Select All Option for MatSelect</a> appeared first on <a href="https://onthecode.co.uk">onthecode</a>.</p>
]]></description>
										<content:encoded><![CDATA[</p>
<p>In this post, you&#8217;ll learn how to implement select all option for <a href="https://material.angular.io/components/select/overview" target="_blank" rel="noreferrer noopener">mat-select</a> from <a href="/blog/category/angular-material" target="_blank" rel="noreferrer noopener">Angular Material</a>. </p>
</p>
<p>Our solution will involve creating a custom component that will be embedded inside a select dropdown. It will also support indeterminate mode of checkbox, meaning our new option will show a different icon based on selected options.</p>
</p>
<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" src="https://onthecode.co.uk/wp-content/uploads/2019/02/Select-all-option-in-mat-select.gif" alt="Select all option in mat-select" class="wp-image-4261" width="370" height="181"/><figcaption>Select all option in mat-select</figcaption></figure>
</div>
</p>
<h2 class="wp-block-heading" id="why-do-you-need-a-select-all-option">Why do you need a select all option?</h2>
</p>
<p><a href="/blog/category/angular-material" target="_blank" rel="noreferrer noopener">Angular Material</a> select component has a multi-select feature, which allows users to check multiple options. Unfortunately, there is no way to display select all option out-of-the-box. </p>
</p>
<p>I can sometimes be useful to select/deselect all options in mat-select dropdown when there are several options.  For example, a user may want to select all Projects in a dropdown. Instead of clicking one by one, they can save time by clicking a single option. </p>
</p>
<p>Therefore, we can build a re-usable select all option to make our users life easier!</p>
</p>
<h2 class="wp-block-heading" id="step-1-create-a-component-for-select-all-option">Step #1: Create a component for select all option </h2>
</p>
<p>Firstly, let&#8217;s generate a new component to make the select all logic reusable:</p>
</p>
<pre class="wp-block-code"><code>ng generate component select-check-all</code></pre>
</p>
<p>Then, place a <code>mat-checkbox</code> inside the component template. This is the <strong>Select all</strong> option.</p>
</p>
<pre class="wp-block-code"><code>&lt;mat-checkbox class="mat-option" &#91;indeterminate]="isIndeterminate()"
&#91;checked]="isChecked()" (click)="$event.stopPropagation()"
    (change)="toggleSelection($event)"&gt;
  {{text}}
&lt;/mat-checkbox&gt;</code></pre>
</p>
<p>After that, set the CSS class to <code>mat-option</code> so that its styling is consistent with other options in <code>mat-select</code>.</p>
</p>
<p>Using data-binding, we update the <code>indeterminate</code> and <code>checked</code> state of the checkbox. This is important to show an icon representing the state of the <code>mat-select</code>.</p>
</p>
<p>Moreover, the checkbox needs to have access to the <code>mat-select</code>. Using reactive forms, we will pass in the form control and the list of values to the checkbox.</p>
</p>
<p>Let&#8217;s take a look at the component implementation:</p>
</p>
<pre class="wp-block-code"><code>import { Component, Input, ViewEncapsulation } from '@angular/core';
import { FormControl } from '@angular/forms';
import { MatCheckboxChange } from '@angular/material';

@Component({
  selector: 'app-select-check-all',
  templateUrl: "./select-check-all.component.html",
  styleUrls: &#91;'./select-check-all.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class SelectCheckAllComponent {
  @Input() model: FormControl;
  @Input() values = &#91;];
  @Input() text = 'Select All'; 

  isChecked(): boolean {
    return this.model.value &amp;&amp; this.values.length
      &amp;&amp; this.model.value.length === this.values.length;
  }

  isIndeterminate(): boolean {
    return this.model.value &amp;&amp; this.values.length &amp;&amp; this.model.value.length &amp;&amp; this.model.value.length &lt; this.values.length;
  }

  toggleSelection(change: MatCheckboxChange): void {
    if (change.checked) {
      this.model.setValue(this.values);
    } else {
      this.model.setValue(&#91;]);
    }
  }
}
</code></pre>
</p>
<p>Notice we use <code>@Input</code> variables to pass the form control, selectable values and display text. </p>
</p>
<p>Finally, add the following styles so that the checkbox takes up full width. </p>
</p>
<pre class="wp-block-code"><code>app-select-check-all .mat-checkbox-layout,
app-select-check-all .mat-checkbox-label {
  width:100% !important;
}</code></pre>
</p>
<h2 class="wp-block-heading" id="step-2-embed-custom-component-in-a-mat-select">Step #2: Embed custom component in a mat-select</h2>
</p>
<p>At last, we can use the custom component to select all options within a <code>mat-select</code>. </p>
</p>
<p>Start by creating a form and add a <code>mat-select</code> with multiple selection.</p>
</p>
<p>Above the loop for generating options, add the <code>app-select-check-all</code> component. This way, our custom component will appear as the first item in the list.</p>
</p>
<p>Don&#8217;t forget to pass in the form control value and the full list of values into <code>app-select-check-all</code> component.</p>
</p>
<pre class="wp-block-code"><code>&lt;form &#91;formGroup]="form"&gt;
	&lt;mat-form-field class="full-width"&gt;
		&lt;mat-select placeholder="Projects" formControlName="project" multiple&gt;
			&lt;app-select-check-all &#91;model]="form.get('project')" &#91;values]="projects"&gt;
			&lt;/app-select-check-all&gt;
			&lt;mat-option *ngFor="let project of projects" &#91;value]="project"&gt;{{ project.name }}&lt;/mat-option&gt;
		&lt;/mat-select&gt;
	&lt;/mat-form-field&gt;
&lt;/form&gt;</code></pre>
</p>
<pre class="wp-block-code"><code>import { Component } from '@angular/core';
import { FormGroup, FormControl } from "@angular/forms";
import { Project } from "./project";
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
  projects:Project&#91;];
  form: FormGroup;
  constructor() { 
    // Create sample projects
    this.projects = &#91;
      new Project("Project 1"),
      new Project("Project 2")
    ]
    // Setup form
    this.form = new FormGroup({
      project: new FormControl(this.projects)      
    });
  }
}</code></pre>
</p>
<h2 class="wp-block-heading" id="live-demo">Live demo</h2>
</p>
<p>Here is a stackblitz project demonstrating select all option for mat-select:</p>
</p>
<p>
<iframe width="100%" height="400px" src="https://stackblitz.com/edit/select-all-option-angular-material?ctl=1&amp;embed=1&amp;file=src/app/app.component.html"></iframe>
</p>
</p>
<h2 class="wp-block-heading" id="summary">Summary</h2>
</p>
<p>In conclusion, you learned how to select all options in Angular Material Select with a custom checkbox component. This custom behaviour provides a way for user to quickly select all options. </p>
</p>
<p>Did you find this useful? Let me know in the comments below!</p></p>
<p>The post <a href="https://onthecode.co.uk/blog/select-all-option-mat-select">Select All Option for MatSelect</a> appeared first on <a href="https://onthecode.co.uk">onthecode</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://onthecode.co.uk/blog/select-all-option-mat-select/feed</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
			</item>
		<item>
		<title>How to Force Selection in Angular Material Autocomplete</title>
		<link>https://onthecode.co.uk/blog/force-selection-angular-material-autocomplete</link>
					<comments>https://onthecode.co.uk/blog/force-selection-angular-material-autocomplete#comments</comments>
		
		<dc:creator><![CDATA[Umut Esen]]></dc:creator>
		<pubDate>Wed, 06 Feb 2019 09:00:44 +0000</pubDate>
				<category><![CDATA[Angular Material]]></category>
		<category><![CDATA[angular material autocomplete]]></category>
		<guid isPermaLink="false">https://onthecode.co.uk/?p=1018</guid>

					<description><![CDATA[<p>In this post, we&#8217;ll look at how to validate autocomplete component from Angular Material. Working with reactive forms, we&#8217;ll write a custom validator to force selection only from the list of options. The autocomplete component is an input with a dropdown of suggested options. It allows the user to type into the input and filter list of options. Then, the user can choose an option. Unfortunately, it does not validate text value against the list of options. Create custom validator for autocomplete Working with reactive forms, the easiest way to solve this issue is to write a custom form validator. Firstly, let&#8217;s create a new file requireMatch.ts: This function evaluates the value of a control and return a validation error if the value is a string type. In detail, AbstractControl parameter allows us to read the current value of any form control. If the type of value is just text, we return an error code incorrect. Otherwise, we return null to indicate no errors. All form controls can make use of this validator function. Use validator in form We can now import the function into your component and pass it into the form control constructor. In the snippet below, I created a simple FormGroup with an autocomplete control to select a project from a list. In addition to adding a required validator, we specify RequireMatch validator on the validators array. With the form group is configured, we are now able to display an error message in the template: Source code is available on GitHub. Summary In summary, I explained how to implement a custom validator to force option selection for Angular Material autocomplete component. This validator basically makes the autocomplete a hybrid between a select and an autocomplete.</p>
<p>The post <a href="https://onthecode.co.uk/blog/force-selection-angular-material-autocomplete">How to Force Selection in Angular Material Autocomplete</a> appeared first on <a href="https://onthecode.co.uk">onthecode</a>.</p>
]]></description>
										<content:encoded><![CDATA[</p>
<p>In this post, we&#8217;ll look at how to validate autocomplete component from <a href="/blog/category/angular-material" target="_blank" rel="noreferrer noopener">Angular Material</a>. Working with reactive forms, we&#8217;ll write a custom validator to force selection only from the list of options.</p>
</p>
<p>
</p>
</p>
<p>The autocomplete component is an input with a dropdown of suggested options. It allows the user to type into the input and filter list of options. Then, the user can choose an option. </p>
</p>
<p><a href="https://material.angular.io/components/autocomplete/overview#simple-autocomplete"></a>Unfortunately, it does not validate text value against the list of options. </p>
</p>
<div class="wp-block-image">
<figure class="aligncenter is-resized"><img loading="lazy" decoding="async" src="https://onthecode.co.uk/wp-content/uploads/2019/02/Autocomplete.jpg" alt="" class="wp-image-1488" width="454" height="194" srcset="https://onthecode.co.uk/wp-content/uploads/2019/02/Autocomplete.jpg 700w, https://onthecode.co.uk/wp-content/uploads/2019/02/Autocomplete-300x129.jpg 300w" sizes="(max-width: 454px) 100vw, 454px" /><figcaption>Autocomplete Force Selection</figcaption></figure>
</div>
<p>
<iframe src="https://stackblitz.com/edit/angular-material-force-selection-autocomplete-component?ctl=1&amp;embed=1&amp;file=src/app/app.component.ts" width="100%" height="400px"></iframe>
</p>
</p>
<h2 class="wp-block-heading" id="create-custom-validator-for-autocomplete">Create custom validator for autocomplete</h2>
</p>
<p>Working with reactive forms, the easiest way to solve this issue is to write a custom form validator.</p>
</p>
<p>Firstly, let&#8217;s create a new file <code>requireMatch.ts</code>:</p>
</p>
<pre class="wp-block-code"><code>import { AbstractControl } from '@angular/forms';
export function RequireMatch(control: AbstractControl) {
    const selection: any = control.value;
    if (typeof selection === 'string') {
        return { incorrect: true };
    }
    return null;
}</code></pre>
</p>
<p>This function evaluates the value of a control and return a validation error if the value is a <code>string</code> type. </p>
</p>
<p>In detail, <code>AbstractControl</code> parameter allows us to read the current value of any form control. If the type of value is just text, we return an error code <code>incorrect</code>. Otherwise, we return null to indicate no errors.</p>
</p>
<p>All form controls can make use of this validator function. </p>
</p>
<h2 class="wp-block-heading" id="use-validator-in-form">Use validator in form</h2>
</p>
<p>We can now import the function into your component and pass it into the form control constructor.</p>
</p>
<p>In the snippet below, I created a simple <code>FormGroup</code> with an autocomplete control to select a project from a list. In addition to adding a required validator, we specify <code>RequireMatch</code> validator on the validators array. </p>
</p>
<pre class="wp-block-code"><code>import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { Project } from './project';
import { RequireMatch as RequireMatch } from './requireMatch';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: &#091;'./app.component.css']
})
export class AppComponent implements OnInit {
  form: FormGroup;
  projects: Project&#091;] = &#091;
      new Project("Web Development"),
      new Project("UX"),
      new Project("SEO")
    ];

  ngOnInit() {
    this.form = new FormGroup({
      project: new FormControl('', &#091;Validators.required, RequireMatch]),
    });
  }
  displayWith(obj?: any): string | undefined {
    return obj ? obj.name : undefined;
  }
}</code></pre>
</p>
<p>With the form group is configured, we are now able to display an error message in the template:</p>
</p>
<pre class="wp-block-code"><code>&lt;form &#091;formGroup]="form"&gt;
    &lt;mat-form-field class="full-width"&gt;
        &lt;input type="text" placeholder="Project" matInput formControlName="project"
 &#091;matAutocomplete]="projectAutoComplete"&gt;
        &lt;mat-autocomplete #projectAutoComplete="matAutocomplete" &#091;displayWith]="displayWith"&gt;
            &lt;mat-option *ngFor="let project of projects" &#091;value]="project"&gt;
                {{ project.name }}
            &lt;/mat-option&gt;
        &lt;/mat-autocomplete&gt;
        &lt;mat-error *ngIf="form.controls&#091;'project'].hasError('required')"&gt;
            Please enter a value
        &lt;/mat-error&gt;
        &lt;mat-error *ngIf="form.controls&#091;'project'].hasError('incorrect')"&gt;
            Please select a valid project
        &lt;/mat-error&gt;
    &lt;/mat-form-field&gt;
&lt;/form&gt;</code></pre>
</p>
<p>Source code is available on <a rel="noreferrer noopener" href="https://github.com/umutesen/AngularMaterialAutoCompleteForceSelection" target="_blank">GitHub</a>.</p>
</p>
<h2 class="wp-block-heading" id="summary">Summary</h2>
</p>
<p>In summary, I explained how to implement a custom validator to force option selection for Angular Material autocomplete component. This validator basically makes the autocomplete a hybrid between a select and an autocomplete.</p></p>
<p>The post <a href="https://onthecode.co.uk/blog/force-selection-angular-material-autocomplete">How to Force Selection in Angular Material Autocomplete</a> appeared first on <a href="https://onthecode.co.uk">onthecode</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://onthecode.co.uk/blog/force-selection-angular-material-autocomplete/feed</wfw:commentRss>
			<slash:comments>16</slash:comments>
		
		
			</item>
		<item>
		<title>Calendar Component in Angular Material</title>
		<link>https://onthecode.co.uk/blog/angular-material-calendar-component</link>
					<comments>https://onthecode.co.uk/blog/angular-material-calendar-component#comments</comments>
		
		<dc:creator><![CDATA[Umut Esen]]></dc:creator>
		<pubDate>Mon, 04 Feb 2019 08:30:03 +0000</pubDate>
				<category><![CDATA[Angular Material]]></category>
		<category><![CDATA[angular 7]]></category>
		<category><![CDATA[angular material calendar]]></category>
		<category><![CDATA[angular material tutorial]]></category>
		<category><![CDATA[mat-calendar]]></category>
		<category><![CDATA[npm]]></category>
		<category><![CDATA[typescript]]></category>
		<guid isPermaLink="false">https://onthecode.co.uk/?p=1203</guid>

					<description><![CDATA[<p>In this post, you&#8217;ll learn how to use Angular Material calendar component without date picker input. The calendar component allows date selection in a month view, which could be useful for a wide range of use cases such as booking forms. In addition to displaying a calendar, we will validate user input and highlight dates on the calendar. Date picker component Material docs have extensive documentation on the date picker component. This is a component that renders an input to let the user select a date from a calendar popup. While this is useful in a data-entry form, it is not always the best way to get date value from the user. It is sometimes necessary to display a calendar that is always open. As there isn&#8217;t an official Material component that works as a stand-alone calendar, I decided to take a deeper look at how the date picker works internally.. I discovered that the date picker brings along an additional component: mat-calendar. This is the component that the user sees on interaction with the date input. Good news for us is that it is fully-functional with data binding and events. Calendar component Please follow the getting started guide, if this is your first time working with Material UI components. Once that is done, it is possible to use the calendar by using mat-calendar selector: This will render the calendar component as below: As the component has an id, ViewChild property decorator can access the calendar element: Calendar component events As there is no documentation for this component, I had to figure things out myself. It appears the calendar component has two events that we can listen to: selectedChange and monthSelected. Event #1: selectedChange This event fires when there is a change in date selection. The event handler argument contains the wewly selected date object. Event #2: monthSelected As the name suggests this event fires when the user changes the currently displayed month. Similarly, the event argument contains the newly selected date object. Unfortunately, this event does not fire when the user interacts with arrow buttons. If you need to access these button clicks, I recommend using the Renderer2 service for wiring-up event handlers. Renderer2 is a WebWorker safe way to manipulate DOM. In this case, selected month can be extracted from the activeDate property. How to validate date selection While displaying a calendar is great, we need a way to validate input. It is not uncommon to validate selection in a calendar control, such as restricting selection to a date range. The date picker allows us to set min and max dates for validation, which disables invalid dates in the calendar popup. How can we do the same in the calendar control? Having looked at the source code for MatCalendar, it appears to have minDate and maxDate properties. It turns out these properties also support data binding so we can implement calendar validation using regular typescript variables. Here I am binding component variables to minDate and maxDate properties so that the calendar updates itself to limit the selectable date range: How to highlight dates on the calendar Going beyond the simple input validation, you may be wondering how to highlight specific days on the calendar. For example, a booking form with a calendar would highlight days that are available. This would draw the attention of the user to those dates. We can use the Renderer2 service to manipulate the HTML output of the calendar component. This allows us to add and remove CSS classes and attributes. Detailed explanation of how the method above works: Retrieve all HTML elements that represent a day in current month view Filter out the days we are not interested in, by checking the value of aria-label The aria label contains the date in specific format: March 20, 2019 Add a custom CSS class available to highlight a day For the purpose of this demo, we can just use a hand-crafted array of dates to highlight couple of days in January 2022. If you need to get these dates from a backend service, you may need to find the current month and year visible on the calendar: Finally, we just need to add styles to actually highlight the days: ::ng-deep is necessary if you are not using the main styles.css of your Angular application. How to disable dates on the calendar Several readers have asked how to disable dates on the calendar component. Following a similar approach to highlighting days, we can disable days using the Renderer2 service. Again, we go through the HTML elements of the calendar and add disabled attribute to days we want to disable. As each day in the calendar is actually a td element (not a button!), the disabled attribute has no effect on its own.. CSS can help us here. Using pointer-events, we disable the click event. Also, let&#8217;s add a background-color to make disabled days more prominent. Custom Angular Material calendar component Since we&#8217;re likely to add custom functionality around the calendar component, it makes a lot of sense to create a reusable component for it. Generate a new component called Calendar. If your application has a shared module, the calendar should be placed there as you&#8217;re likely to use it across feature modules. Add the necessary HTML markup of the mat-calendar component in the template: I have added buttons above the calendar to demonstrate two-way binding. These buttons will set the current date of the calendar to previous day, today or next day. Let&#8217;s also add some styling so that the calendar does not take up the full width of the page: Implement the calendar in the component as shown below. The component is pretty simple &#8211; we&#8217;ve put together a component that exposes a dateSelected event that fires whenever the selected date changes. Here is how to use the calendar component: Summary In this post, we got our hands dirty with the Angular Material calendar component. I have been using this in a real-world application</p>
<p>The post <a href="https://onthecode.co.uk/blog/angular-material-calendar-component">Calendar Component in Angular Material</a> appeared first on <a href="https://onthecode.co.uk">onthecode</a>.</p>
]]></description>
										<content:encoded><![CDATA[</p>
<p>In this post, you&#8217;ll learn how to use <a href="/blog/category/angular-material" target="_blank" rel="noreferrer noopener">Angular Material</a> calendar component without date picker input. The calendar component allows date selection in a month view, which could be useful for a wide range of use cases such as booking forms.</p>
</p>
<p>In addition to displaying a calendar, we will validate user input and highlight dates on the calendar. </p>
</p>
<h2 class="wp-block-heading" id="date-picker-component">Date picker component</h2>
</p>
<p>Material docs have extensive documentation on the <a href="https://material.angular.io/components/datepicker/overview" target="_blank" rel="noreferrer noopener">date picker</a> component. This is a component that renders an input to let the user select a date from a calendar popup. </p>
</p>
<p>While this is useful in a data-entry form, it is not always the best way to get date value from the user. It is sometimes necessary to display a calendar that is always open.</p>
</p>
<figure class="wp-block-image aligncenter size-large is-resized"><img loading="lazy" decoding="async" src="https://onthecode.co.uk/wp-content/uploads/2022/01/Angular-Material-Datepicker-1024x747.png" alt="Date picker component" class="wp-image-3712" width="536" height="390" title="Date picker component" srcset="https://onthecode.co.uk/wp-content/uploads/2022/01/Angular-Material-Datepicker-1024x747.png 1024w, https://onthecode.co.uk/wp-content/uploads/2022/01/Angular-Material-Datepicker-300x219.png 300w, https://onthecode.co.uk/wp-content/uploads/2022/01/Angular-Material-Datepicker-768x560.png 768w, https://onthecode.co.uk/wp-content/uploads/2022/01/Angular-Material-Datepicker.png 1248w" sizes="(max-width: 536px) 100vw, 536px" /><figcaption>Date picker component</figcaption></figure>
</p>
<p>As there isn&#8217;t an official Material component that works as a stand-alone calendar, I decided to take a deeper look at how the date picker works internally..</p>
</p>
<p>I discovered that the date picker brings along an additional component: <code>mat-calendar</code>. This is the component that the user sees on interaction with the date input. </p>
</p>
<p>Good news for us is that it is fully-functional with data binding and events.</p>
</p>
<h2 class="wp-block-heading" id="calendar-component">Calendar component</h2>
</p>
<p>Please follow the <a href="https://material.angular.io/guide/getting-started" target="_blank" rel="noreferrer noopener">getting started guide</a>, if this is your first time working with Material UI components.</p>
</p>
<p>Once that is done, it is possible to use the calendar by using <code>mat-calendar</code> selector:</p>
</p>
<pre class="wp-block-code"><code>&lt;div class="calendar-wrapper"&gt;
    &lt;mat-calendar #calendar &#91;(selected)]="selectedDate"&gt;
    &lt;/mat-calendar&gt;
&lt;/div&gt;</code></pre>
</p>
<p>This will render the calendar component as below:</p>
</p>
<figure class="wp-block-image aligncenter size-large is-resized"><img loading="lazy" decoding="async" src="https://onthecode.co.uk/wp-content/uploads/2022/01/Angular-Material-Calendar-1024x634.png" alt="Calendar component" class="wp-image-3716" width="519" height="321" title="Date picker component" srcset="https://onthecode.co.uk/wp-content/uploads/2022/01/Angular-Material-Calendar-1024x634.png 1024w, https://onthecode.co.uk/wp-content/uploads/2022/01/Angular-Material-Calendar-300x186.png 300w, https://onthecode.co.uk/wp-content/uploads/2022/01/Angular-Material-Calendar-768x475.png 768w, https://onthecode.co.uk/wp-content/uploads/2022/01/Angular-Material-Calendar.png 1228w" sizes="(max-width: 519px) 100vw, 519px" /><figcaption>Calendar component</figcaption></figure>
</p>
<p>As the component has an id, <code>ViewChild</code> property decorator can access the calendar element:</p>
</p>
<pre class="wp-block-code"><code> @ViewChild('calendar') calendar: MatCalendar&lt;Moment&gt;;
 selectedDate: Moment;</code></pre>
</p>
<h2 class="wp-block-heading" id="calendar-component-events">Calendar component events</h2>
</p>
<p>As there is no documentation for this component, I had to figure things out myself. </p>
</p>
<p> It appears the calendar component has two events that we can listen to: <code>selectedChange</code> and <code>monthSelected</code>.</p>
</p>
<h3 class="wp-block-heading" id="event-1-selectedchange">Event #1: selectedChange</h3>
</p>
<p>This event fires when there is a change in date selection. </p>
</p>
<p>The event handler argument contains the wewly selected date object.</p>
</p>
<pre class="wp-block-code"><code>&lt;mat-calendar #calendar &#91;(selected)]="selectedDate" 
              (selectedChange)="dateChanged($event)"&gt;
&lt;/mat-calendar&gt;</code></pre>
</p>
<pre class="wp-block-code"><code>dateChanged(date) {
  alert(`Selected: ${date}`);
}</code></pre>
</p>
<h3 class="wp-block-heading" id="event-2-monthselected">Event #2: monthSelected</h3>
</p>
<p>As the name suggests this event fires when the user changes the currently displayed month.</p>
</p>
<p>Similarly, the event argument contains the newly selected date object.</p>
</p>
<pre class="wp-block-code"><code>&lt;mat-calendar #calendar &#91;(selected)]="selectedDate" 
              (monthSelected)="monthSelected($event)"&gt;
&lt;/mat-calendar&gt;</code></pre>
</p>
<pre class="wp-block-code"><code>monthSelected(date) {
  alert(`Selected: ${date}`);
}</code></pre>
</p>
<p>Unfortunately, this event does not fire when the user interacts with arrow buttons. </p>
</p>
<p>If you need to access these button clicks, I recommend using the <code>Renderer2</code> service for wiring-up event handlers. Renderer2 is a WebWorker safe way to manipulate DOM. </p>
</p>
<p>In this case, selected month can be extracted from the <code>activeDate</code> property.</p>
</p>
<pre class="wp-block-code"><code>ngAfterViewInit() {
  const buttons = document
   .querySelectorAll('.mat-calendar-previous-button, .mat-calendar-next-button');
  
  if (buttons) {
    Array.from(buttons).forEach(button =&gt; {
      this.renderer.listen(button, 'click', () =&gt; {
        alert('Arrow buttons clicked');
        // this.calendar.activeDate;
      });
    });
  }
}</code></pre>
</p>
<h2 class="wp-block-heading" id="how-to-validate-date-selection">How to validate date selection</h2>
</p>
<p>While displaying a calendar is great, we need a way to validate input. It is not uncommon to validate selection in a calendar control, such as restricting selection to a date range. </p>
</p>
<p>The date picker allows us to set <code>min</code> and <code>max</code> dates for validation, which disables invalid dates in the calendar popup. How can we do the same in the calendar control?</p>
</p>
<p>Having looked at the source code for <code>MatCalendar</code>, it appears to have <code>minDate</code> and <code>maxDate</code> properties.</p>
</p>
<p>It turns out these properties also support data binding so we can implement calendar validation using regular typescript variables.</p>
</p>
<pre class="wp-block-code"><code>// from docs
export declare class MatCalendar&lt;D&gt; implements AfterContentInit, AfterViewChecked, OnDestroy, OnChanges {
    //......
    /** The minimum selectable date. */
    minDate: D | null;
    private _minDate;
    /** The maximum selectable date. */
    maxDate: D | null;
    private _maxDate;
    //.....
}</code></pre>
</p>
<p>Here I am binding component variables to <code>minDate</code> and <code>maxDate</code> properties so that the calendar updates itself to limit the selectable date range:</p>
</p>
<pre class="wp-block-code"><code>&lt;mat-calendar #calendar &#91;minDate]="minDate" &#91;maxDate]="maxDate"&gt;&lt;/mat-calendar&gt;</code></pre>
</p>
<h2 class="wp-block-heading" id="how-to-highlight-dates-on-the-calendar">How to highlight dates on the calendar</h2>
</p>
<p>Going beyond the simple input validation, you may be wondering how to highlight specific days on the calendar. </p>
</p>
<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="333" height="443" src="https://onthecode.co.uk/wp-content/uploads/2022/01/Highlight-dates-on-material-calendar.png" alt="Dates highlighted on the calendar" class="wp-image-4188" title="Dates highlighted on the calendar" srcset="https://onthecode.co.uk/wp-content/uploads/2022/01/Highlight-dates-on-material-calendar.png 333w, https://onthecode.co.uk/wp-content/uploads/2022/01/Highlight-dates-on-material-calendar-226x300.png 226w" sizes="(max-width: 333px) 100vw, 333px" /><figcaption>Dates highlighted on calendar</figcaption></figure>
</p>
<p>For example, a booking form with a calendar would highlight days that are available. This would draw the attention of the user to those dates.</p>
</p>
<p>We can use the <code>Renderer2</code> service to manipulate the HTML output of the calendar component. This allows us to add and remove CSS classes and attributes.</p>
</p>
<pre class="wp-block-code"><code>  /**
   * Method to highlight certain days on the calendar.
   * This should be used when month selection changes.
   * 
   * @param days: Array of strings in the format "February 20, 2020"
   */
  private highlightDays(days: string&#91;]) {
    const dayElements = document.querySelectorAll(
      'mat-calendar .mat-calendar-table .mat-calendar-body-cell'
    );

    Array.from(dayElements).forEach((element) =&gt; {
      const matchingDay = days.find((d) =&gt; d === element.getAttribute('aria-label')) !== undefined;

      if (matchingDay) {
        this.renderer.addClass(element, 'available');
        this.renderer.setAttribute(element, 'title', 'Event 1');
      } else {
        this.renderer.removeClass(element, 'available');
        this.renderer.removeAttribute(element, 'title');
      }
    });
  }</code></pre>
</p>
<p>Detailed explanation of how the method above works:</p>
</p>
<ol class="wp-block-list">
<li>Retrieve all HTML elements that represent a day in current month view</li>
<li>Filter out the days we are not interested in, by checking the value of <code>aria-label</code>
<ol>
<li>The aria label contains the date in specific format: <strong>March 20, 2019</strong></li>
</ol>
</li>
<li>Add a custom CSS class <code>available</code> to highlight a day</li>
</ol>
</p>
<p>For the purpose of this demo, we can just use a hand-crafted array of dates to highlight couple of days in January 2022. If you need to get these dates from a backend service, you may need to find the current month and year visible on the calendar:</p>
</p>
<pre class="wp-block-code"><code>//// Get current month/year selected in calendar to facilitate backend call
const month = parseInt(this.calendar.activeDate.format('M'));
const year = parseInt(this.calendar.activeDate.format('Y'));
this.backendService.getAvailableDays(month, year); // Expected format: &#91;"February 20, 2020"]</code></pre>
</p>
<p>Finally, we just need to add styles to actually highlight the days:</p>
</p>
<pre class="wp-block-code"><code>::ng-deep .available .mat-calendar-body-cell-content{
    background-color: rgba(14, 152, 5, 0.25);
}</code></pre>
</p>
<p><code>::ng-deep</code> is necessary if you are not using the main <code>styles.css</code> of your Angular application.</p>
</p>
<h2 class="wp-block-heading" id="how-to-disable-dates-on-the-calendar">How to disable dates on the calendar</h2>
</p>
<p>Several readers have asked how to disable dates on the calendar component. </p>
</p>
<figure class="wp-block-image aligncenter size-full is-resized"><img loading="lazy" decoding="async" src="https://onthecode.co.uk/wp-content/uploads/2022/02/Angular-Material-Calendar-Component-Disabled-Dates.png" alt="Angular Material Calendar Component Disabled Dates" class="wp-image-4217" width="333" height="445" title="Angular Material Calendar Component Disabled Dates" srcset="https://onthecode.co.uk/wp-content/uploads/2022/02/Angular-Material-Calendar-Component-Disabled-Dates.png 668w, https://onthecode.co.uk/wp-content/uploads/2022/02/Angular-Material-Calendar-Component-Disabled-Dates-225x300.png 225w" sizes="(max-width: 333px) 100vw, 333px" /><figcaption>Dates disabled on calendar</figcaption></figure>
</p>
<p>Following a similar approach to highlighting days, we can disable days using the <code>Renderer2</code> service.</p>
</p>
<pre class="wp-block-code"><code>  /**
   * Method to disable certain days on the calendar.
   * This should be used when month selection changes.
   * 
   * @param days: Array of strings in the format "February 20, 2020"
   */
  private disableDays(days: string&#91;]) {
    const dayElements = document.querySelectorAll(
      'mat-calendar .mat-calendar-table .mat-calendar-body-cell'
    );

    Array.from(dayElements).forEach((element) =&gt; {
      const matchingDay = days.find((d) =&gt; d === element.getAttribute('aria-label')) !== undefined;

      if (matchingDay) {
        this.renderer.setAttribute(element, 'disabled', '');
        this.renderer.setAttribute(element, 'title', 'Unavailable');
      } else {
        this.renderer.removeAttribute(element, 'disabled');
        this.renderer.removeAttribute(element, 'title');
      }
    });
  }</code></pre>
</p>
<p>Again, we go through the HTML elements of the calendar and add <code>disabled</code> attribute to days we want to disable. </p>
</p>
<p>As each day in the calendar is actually a <code>td</code> element (not a button!), the <code>disabled</code> attribute has no effect on its own..</p>
</p>
<p>CSS can help us here. Using <code>pointer-events</code>, we disable the click event. </p>
</p>
<p>Also, let&#8217;s add a <code>background-color</code> to make disabled days more prominent.</p>
</p>
<pre class="wp-block-code"><code>::ng-deep .mat-calendar-body-cell&#91;disabled]{
    pointer-events: none;
}
::ng-deep .mat-calendar-body-cell&#91;disabled] .mat-calendar-body-cell-content {
    background-color: rgba(128, 128, 128, 0.637);
}</code></pre>
</p>
<h2 class="wp-block-heading" id="custom-angular-material-calendar-component">Custom Angular Material calendar component  </h2>
</p>
<p>Since we&#8217;re likely to add custom functionality around the calendar component, it makes a lot of sense to create a reusable component for it. </p>
</p>
<p>Generate a new component called <code>Calendar</code>. If your application has a shared module, the calendar should be placed there as you&#8217;re likely to use it across feature modules. </p>
</p>
<pre class="wp-block-code"><code>ng generate component Calendar</code></pre>
</p>
<p>Add the necessary HTML markup of the <code>mat-calendar</code> component in the template:</p>
</p>
<pre class="wp-block-code"><code>&lt;div class="calendar-wrapper"&gt;
  &lt;button mat-button (click)="prevDay()"&gt;Prev&lt;/button&gt;
  &lt;button mat-button (click)="today()"&gt;Today&lt;/button&gt;
  &lt;button mat-button (click)="nextDay()"&gt;Next&lt;/button&gt;

  &lt;mat-calendar #calendar &#91;minDate]="minDate" &#91;maxDate]="maxDate" (monthSelected)="monthChanged($event)" &#91;(selected)]="selectedDate"
    (selectedChange)="dateChanged()"&gt;&lt;/mat-calendar&gt;

  &lt;button (click)="setMinDate()"&gt;Set min date&lt;/button&gt;
  &lt;button (click)="setMaxDate()"&gt;Set max date&lt;/button&gt;
&lt;/div&gt;</code></pre>
</p>
<p>I have added buttons above the calendar to demonstrate two-way binding. These buttons will set the current date of the calendar to previous day, today or next day. </p>
</p>
<p>Let&#8217;s also add some styling so that the calendar does not take up the full width of the page:</p>
</p>
<pre class="wp-block-code"><code>.calendar-wrapper {
    width: 300px;
    text-align: center;
}</code></pre>
</p>
<p>Implement the calendar in the component as shown below.</p>
</p>
<pre class="wp-block-code"><code>import * as moment from 'moment';

import {
    AfterViewInit, Component, EventEmitter, Output, Renderer2, ViewChild
} from '@angular/core';
import { MatCalendar } from '@angular/material';

@Component({
  selector: 'app-calendar',
  templateUrl: './calendar.component.html',
  styleUrls: &#91;'./calendar.component.css']
})
export class CalendarComponent implements AfterViewInit {
  selectedDate = moment();
  minDate: moment.Moment;
  maxDate: moment.Moment;

  @Output()
  dateSelected: EventEmitter&lt;moment.Moment&gt; = new EventEmitter();

  @Output()
  monthSelected: EventEmitter&lt;moment.Moment&gt; = new EventEmitter();

  @ViewChild('calendar', { static: true })
  calendar: MatCalendar&lt;moment.Moment&gt;;

  constructor(private renderer: Renderer2) { }

  setMinDate() {
    this.minDate = moment().add(-10, 'day');
  }

  setMaxDate() {
    this.maxDate = moment().add(10, 'day');
  }

  ngAfterViewInit() {
    this.setupArrowButtonListeners();
  }

  private setupArrowButtonListeners() {
    const buttons = document.querySelectorAll('.mat-calendar-previous-button, .mat-calendar-next-button');

    if (buttons) {
      Array.from(buttons).forEach(button =&gt; {
        this.renderer.listen(button, 'click', () =&gt; {
          this.monthSelected.emit(this.calendar.activeDate);
        });
      });
    }
  }

  monthChanged(date: moment.Moment) {
    this.monthSelected.emit(date);
  }

  dateChanged() {
    this.calendar.activeDate = this.selectedDate;
    this.dateSelected.emit(this.selectedDate);
  }

  prevDay() {
    const prevMoment = moment(this.selectedDate).add(-1, 'days');
    this.selectedDate = prevMoment;
    this.dateChanged();
  }

  today() {
    this.selectedDate = moment();
    this.dateChanged();
  }

  nextDay() {
    const nextMoment = moment(this.selectedDate).add(1, 'days');
    this.selectedDate = nextMoment;
    this.dateChanged();
  }
}</code></pre>
</p>
<p>The component is pretty simple &#8211; we&#8217;ve put together a component that exposes a <code>dateSelected</code> event that fires whenever the selected date changes. </p>
</p>
<p>Here is how to use the calendar component:</p>
</p>
<pre class="wp-block-code"><code>&lt;app-calendar (dateSelected)="dateSelected($event)" (monthSelected)="monthSelected($event)"&gt;&lt;/app-calendar&gt;</code></pre>
</p>
<pre class="wp-block-code"><code>import { Moment } from 'moment';
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
  dateSelected(value: Moment) {
    alert(value);
  }

  monthSelected(value: Moment) {
    alert(value);
  }
}</code></pre>
</p>
<h2 class="wp-block-heading" id="summary">Summary</h2>
</p>
<p>In this post, we got our hands dirty with the Angular Material calendar component. I have been using this in a real-world application for quite some time and haven&#8217;t had any issues yet. While the component is very helpful, I am not sure why the documentation does not mention it. If you know the answer, drop a comment below!</p>
</p>
<p><a href="https://github.com/umutesen/material-calendar-demo" target="_blank" rel="noreferrer noopener">View code on GitHub</a></p></p>
<p>The post <a href="https://onthecode.co.uk/blog/angular-material-calendar-component">Calendar Component in Angular Material</a> appeared first on <a href="https://onthecode.co.uk">onthecode</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://onthecode.co.uk/blog/angular-material-calendar-component/feed</wfw:commentRss>
			<slash:comments>21</slash:comments>
		
		
			</item>
		<item>
		<title>Angular Material Confirm Dialog</title>
		<link>https://onthecode.co.uk/blog/create-confirm-dialog-angular-material</link>
					<comments>https://onthecode.co.uk/blog/create-confirm-dialog-angular-material#comments</comments>
		
		<dc:creator><![CDATA[Umut Esen]]></dc:creator>
		<pubDate>Thu, 31 Jan 2019 00:10:37 +0000</pubDate>
				<category><![CDATA[Angular Material]]></category>
		<category><![CDATA[angular 7]]></category>
		<category><![CDATA[angular confirmation dialog]]></category>
		<category><![CDATA[angular material dialog]]></category>
		<category><![CDATA[angular material tutorial]]></category>
		<category><![CDATA[npm]]></category>
		<category><![CDATA[typescript]]></category>
		<guid isPermaLink="false">https://onthecode.co.uk/?p=933</guid>

					<description><![CDATA[<p>It is a common requirement for any Angular application to prompt the user for a confirmation dialog. For instance, you may want to show a message when the user wants to delete a record or send an email. In this post, we will look at how we can implement a reusable component in Angular Material components. Basic confirm dialog in JavaScript Traditionally, web applications make use of the built-in JavaScript API to show confirm dialog as shown below. However, the vanilla JavaScript dialogs are synchronous &#8211; meaning everything on the screen will freeze until the user responds, they can&#8217;t be customised visually and don&#8217;t support images. Angular Material confirm dialog To overcome the limitations of the traditional approach, we can easily build a flexible confirmation dialog in Angular with a bit of help from the Material components. Here is what we are going to build: We will use the Dialog component of Angular Material library to display our confirm dialogs. The dialog takes the focus away from the current window, and forces the browser to read the message. The following are the main features of this custom component: Asynchronous Behaviour: We want to show the dialog and subscribe to its result. This is very important as we don&#8217;t know when the user is going to respond. Asynchrony allows us to properly react to the response of the user. Flexibility: We want to customise the title &#38; message of the confirm dialog so that we can display any message from anywhere in the application. Check out the code on GitHub or view live demo here. Import Angular Material components First of all, you need to import Angular Material to your application. If you need help with this, check out my guide. Once you have access to Material components, import ButtonModule and MatDialogModule. I am importing Material UI components to a feature module called CustomMaterialModule. You can import them directly to the app.module. Generate a component Next, generate a component for the confirmation dialog using the following command: This will automagically create your component and link it with your root app.module. Open the app.module and add the newly-created component to the entryComponents array. This is so that the confirm dialog can be dynamically loaded into the view &#8211; read more about entry components. Implement dialog features Basically, we just want to show a heading, message and buttons to dismiss the dialog. Here is what the template looks like: As you can see, this is a standard Material dialog implementation. The component class to handle UI interaction is as follows: The component just handles the events by closing the Material dialog with the selected result from the view. ConfirmDialogModel is used to pass data into the dialog. Display dialog on button click Finally, we can show our custom confirmation dialog using the code below. Since we use MatDialog component internally, we take in the MatDialog dependency in the constructor and show the confirm dialog on button click. Subscribing to the afterClosed() event of the dialog means that we can get the result and update the view through data-binding. Add a button to the view to trigger the dialog, and a label to show the response: and the component for the functionality: Summary In conclusion, we looked at how we can create a reusable component in Angular to display confirmation dialogs. Similarly, this approach can be used to implement other types of dialogs such as alerts, date/time input dialogs &#38; more. Check out the code on GitHub.</p>
<p>The post <a href="https://onthecode.co.uk/blog/create-confirm-dialog-angular-material">Angular Material Confirm Dialog</a> appeared first on <a href="https://onthecode.co.uk">onthecode</a>.</p>
]]></description>
										<content:encoded><![CDATA[</p>
<p>It is a common requirement for any Angular application to prompt the user for a confirmation dialog. For instance, you may want to show a message when the user wants to delete a record or send an email. In this post, we will look at how we can implement a reusable component in <a href="/category/angular-material">Angular Material</a> components.</p>
</p>
<h2 class="wp-block-heading" id="basic-confirm-dialog-in-javascript">Basic confirm dialog in JavaScript</h2>
</p>
<p>Traditionally, web applications make use of the built-in <code>JavaScript</code> API to show confirm dialog as shown below. </p>
</p>
<p>However, the vanilla JavaScript dialogs are synchronous &#8211; meaning everything on the screen will freeze until the user responds, they can&#8217;t be customised visually and don&#8217;t support images.</p>
</p>
<pre class="wp-block-code"><code>// Display a confirmation prompt
var result = confirm("Are you sure?");</code></pre>
</p>
<figure class="wp-block-image aligncenter is-resized"><img loading="lazy" decoding="async" src="https://onthecode.co.uk/wp-content/uploads/2019/01/JavaScript-confirm-dialog.png" alt="Default JavaScript confirm dialog " class="wp-image-1235" width="389" height="120" srcset="https://onthecode.co.uk/wp-content/uploads/2019/01/JavaScript-confirm-dialog.png 950w, https://onthecode.co.uk/wp-content/uploads/2019/01/JavaScript-confirm-dialog-300x93.png 300w, https://onthecode.co.uk/wp-content/uploads/2019/01/JavaScript-confirm-dialog-768x238.png 768w, https://onthecode.co.uk/wp-content/uploads/2019/01/JavaScript-confirm-dialog-700x217.png 700w" sizes="(max-width: 389px) 100vw, 389px" /><figcaption>Basic JavaScript Confirmation Dialog</figcaption></figure>
</p>
<h2 class="wp-block-heading" id="angular-material-confirm-dialog">Angular Material confirm dialog</h2>
</p>
<p>To overcome the limitations of the traditional approach, we can easily build a flexible confirmation dialog in Angular with a bit of help from the <a href="http://material.angular.io" target="_blank" rel="noreferrer noopener">Material components</a>. </p>
</p>
<p>Here is what we are going to build:</p>
</p>
<figure class="wp-block-image aligncenter is-resized"><img loading="lazy" decoding="async" src="https://onthecode.co.uk/wp-content/uploads/2019/01/Angular-Material-Confirm-Dialog.jpg" alt="Angular Material Confirm Dialog Modal Popup" class="wp-image-1237" width="400" height="224" srcset="https://onthecode.co.uk/wp-content/uploads/2019/01/Angular-Material-Confirm-Dialog.jpg 700w, https://onthecode.co.uk/wp-content/uploads/2019/01/Angular-Material-Confirm-Dialog-300x168.jpg 300w" sizes="(max-width: 400px) 100vw, 400px" /><figcaption>Custom Confirm Dialog in Angular Material</figcaption></figure>
</p>
<p>We will use the <code>Dialog</code> component of Angular Material library to display our confirm dialogs. </p>
</p>
<p>The dialog takes the focus away from the current window, and forces the browser to read the message. The following are the main features of this custom component:</p>
</p>
<ul class="wp-block-list">
<li><strong>Asynchronous Behaviour:</strong> We want to show the dialog and subscribe to its result. This is very important as we don&#8217;t know when the user is going to respond. Asynchrony allows us to properly react to the response of the user.</li>
<li><strong>Flexibility:</strong> We want to customise the title &amp; message of the confirm dialog so that we can display any message from anywhere in the application.</li>
</ul>
</p>
<p>Check out the code on <a href="https://github.com/umutesen/angular-material-confirm-dialog" target="_blank" rel="noreferrer noopener">GitHub</a> or view live demo <a href="https://stackblitz.com/edit/reusable-confirmation-dialog-angular-material" target="_blank" rel="noreferrer noopener">here</a>.</p>
</p>
<h2 class="wp-block-heading" id="import-angular-material-components">Import Angular Material components</h2>
</p>
<p>First of all, you need to import Angular Material to your application. If you need help with this, check out my <a href="https://onthecode.co.uk/import-angular-material-feature-module/" target="_blank" rel="noreferrer noopener">guide</a>.</p>
</p>
<p>Once you have access to Material components, import <code>ButtonModule</code> and <code>MatDialogModule</code>.</p>
</p>
<pre class="wp-block-code"><code>import { NgModule } from '@angular/core';
import { MatButtonModule, MatDialogModule } from '@angular/material';

@NgModule({
  imports: &#91;
    MatButtonModule, MatDialogModule
  ],
  exports: &#91;
    MatButtonModule, MatDialogModule
  ]
})
export class CustomMaterialModule {}</code></pre>
</p>
<p>I am importing Material UI components to a feature module called <code>CustomMaterialModule</code>. </p>
</p>
<p>You can import them directly to the <code>app.module</code>.</p>
</p>
<h2 class="wp-block-heading" id="generate-a-component">Generate a component</h2>
</p>
<p>Next, generate a component for the confirmation dialog using the following command:</p>
</p>
<pre class="wp-block-code"><code>ng generate component ConfirmDialog</code></pre>
</p>
<p>This will automagically create your component and link it with your root <code>app.module</code>. </p>
</p>
<p>Open the <code>app.module</code> and add the newly-created component to the <code>entryComponents</code> array. This is so that the confirm dialog can be dynamically loaded into the view &#8211; <a href="https://angular.io/guide/entry-components">read more about entry components</a>.</p>
</p>
<pre class="wp-block-code"><code>import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { CustomMaterialModule } from './custom-material/custom-material.module';
import { ConfirmDialogComponent } from './confirm-dialog/confirm-dialog.component';

@NgModule({
  declarations: &#91;
    AppComponent,
    ConfirmDialogComponent
  ],
  imports: &#91;
    BrowserModule,
    BrowserAnimationsModule,
    CustomMaterialModule
  ],
  providers: &#91;],
  entryComponents: &#91;ConfirmDialogComponent],
  bootstrap: &#91;AppComponent]
})
export class AppModule {}</code></pre>
</p>
<h2 class="wp-block-heading" id="implement-dialog-features">Implement dialog features</h2>
</p>
<p>Basically, we just want to show a heading, message and buttons to dismiss the dialog.</p>
</p>
<p>Here is what the template looks like:</p>
</p>
<pre class="wp-block-code"><code>&lt;h1 mat-dialog-title&gt;
  {{title}}
&lt;/h1&gt;

&lt;div mat-dialog-content&gt;
  &lt;p&gt;{{message}}&lt;/p&gt;
&lt;/div&gt;

&lt;div mat-dialog-actions&gt;
  &lt;button mat-button (click)="onDismiss()"&gt;No&lt;/button&gt;
  &lt;button mat-raised-button color="primary" (click)="onConfirm()"&gt;Yes&lt;/button&gt;
&lt;/div&gt;</code></pre>
</p>
<p>As you can see, this is a standard Material dialog implementation. </p>
</p>
<p>The component class to handle UI interaction is as follows:</p>
</p>
<pre class="wp-block-code"><code>import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { Component, OnInit, Inject } from '@angular/core';

@Component({
  selector: 'app-confirm-dialog',
  templateUrl: './confirm-dialog.component.html',
  styleUrls: &#91;'./confirm-dialog.component.css']
})
export class ConfirmDialogComponent {
  title: string;
  message: string;

  constructor(public dialogRef: MatDialogRef&amp;lt;ConfirmDialogComponent&gt;,
    @Inject(MAT_DIALOG_DATA) public data: ConfirmDialogModel) {
    // Update view with given values
    this.title = data.title;
    this.message = data.message;
  }
 
  onConfirm(): void {
    // Close the dialog, return true
    this.dialogRef.close(true);
  }

  onDismiss(): void {
    // Close the dialog, return false
    this.dialogRef.close(false);
  }
}

/**
 * Class to represent confirm dialog model.
 *
 * It has been kept here to keep it as part of shared component.
 */
export class ConfirmDialogModel {

  constructor(public title: string, public message: string) {
  }
}</code></pre>
</p>
<p>The component just handles the events by closing the Material dialog with the selected result from the view. </p>
</p>
<p><code>ConfirmDialogModel</code> is used to pass data into the dialog.</p>
</p>
<h2 class="wp-block-heading" id="display-dialog-on-button-click">Display dialog on button click</h2>
</p>
<p>Finally, we can show our custom confirmation dialog using the code below. </p>
</p>
<p>Since we use <a href="https://material.angular.io/components/dialog/overview">MatDialog</a> component internally, we take in the <code>MatDialog</code> dependency in the constructor and show the confirm dialog on button click. </p>
</p>
<p>Subscribing to the <code>afterClosed()</code> event of the dialog means that we can get the result and update the view through data-binding. </p>
</p>
<p>Add a button to the view to trigger the dialog, and a label to show the response:</p>
</p>
<div class="wp-block-group">
<div class="wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow">
<pre class="wp-block-code"><code>&lt;button mat-raised-button color="primary" (click)="confirmDialog()"&gt;Confirm&lt;/button&gt;
&lt;br&gt;
Response is: {{result}}</code></pre>
</div>
</div>
</p>
<p>and the component for the functionality:</p>
</p>
<pre class="wp-block-code"><code>import { Component } from '@angular/core';
import { ConfirmDialogModel, ConfirmDialogComponent } from './confirm-dialog/confirm-dialog.component';
import { MatDialog } from '@angular/material';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
  result: string = '';

  constructor(public dialog: MatDialog) {}

  confirmDialog(): void {
    const message = `Are you sure you want to do this?`;

    const dialogData = new ConfirmDialogModel("Confirm Action", message);

    const dialogRef = this.dialog.open(ConfirmDialogComponent, {
      maxWidth: "400px",
      data: dialogData
    });

    dialogRef.afterClosed().subscribe(dialogResult =&gt; {
      this.result = dialogResult;
    });
  }
}</code></pre>
</p>
<h2 class="wp-block-heading" id="summary">Summary</h2>
</p>
<p>In conclusion, we looked at how we can create a reusable component in Angular to display confirmation dialogs. Similarly, this approach can be used to implement other types of dialogs such as alerts, date/time input dialogs &amp; more. </p>
</p>
<div class="wp-block-buttons is-layout-flex wp-block-buttons-is-layout-flex"></div>
</p>
<p>Check out the code on <a href="https://github.com/umutesen/angular-material-confirm-dialog" target="_blank" rel="noreferrer noopener">GitHub</a>.</p></p>
<p>The post <a href="https://onthecode.co.uk/blog/create-confirm-dialog-angular-material">Angular Material Confirm Dialog</a> appeared first on <a href="https://onthecode.co.uk">onthecode</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://onthecode.co.uk/blog/create-confirm-dialog-angular-material/feed</wfw:commentRss>
			<slash:comments>10</slash:comments>
		
		
			</item>
		<item>
		<title>How to Add Angular Material Components Correctly</title>
		<link>https://onthecode.co.uk/blog/import-angular-material-feature-module</link>
					<comments>https://onthecode.co.uk/blog/import-angular-material-feature-module#comments</comments>
		
		<dc:creator><![CDATA[Umut Esen]]></dc:creator>
		<pubDate>Tue, 29 Jan 2019 18:30:37 +0000</pubDate>
				<category><![CDATA[Angular Material]]></category>
		<category><![CDATA[angular 7]]></category>
		<category><![CDATA[angular best practices]]></category>
		<category><![CDATA[angular material tutorial]]></category>
		<category><![CDATA[angular project setup]]></category>
		<category><![CDATA[npm]]></category>
		<category><![CDATA[typescript]]></category>
		<guid isPermaLink="false">https://onthecode.co.uk/?p=929</guid>

					<description><![CDATA[<p>In this post, I will show you how to add Angular Material components in an Angular application. Importing UI components directly in the app.module increases the size of the module. The root module should be easy to maintain. Importing a button is not a great idea here. For example, consider importing and configuring date picker in several feature modules. In this case, you can avoid duplication by having a single Material module. Add Angular Material First off, let&#8217;s add Angular Material to our project: This command installs Angular Material, the Component Dev Kit (CDK), Angular Animations. It will ask these questions to setup Material according to your needs: Choose a prebuilt theme name, or &#8220;custom&#8221; for a custom theme Set up global Angular Material typography styles? Set up browser animations for Angular Material? Generate feature module Generate a module for keeping Material components: This will not only create a new folder called custom-material but also a module definition for your imports. Next, open up the module definition and import a button: Notice we need to export the button component, which makes it available to any module that imports the CustomMaterialModule. The idea here is that our custom material module will be responsible for any configuration, custom components etc. It should only export things that are needed by consumer modules. At this point, you can import CustomMaterialModule in any other module. We can now use the button in a component: Going forward, you can just import the components from Angular Material into the CustomMaterialModule and use them in your own components. For example, if you need to display icons, you need to import and export MatIconModule from the CustomMaterialModule. Custom components You will reap the benefits of this approach, when the time comes to implement a custom feature into any of the Material components. For example, if you implement a select all option for Select component, you can easily create a custom component inside the CustomMaterialModule and export it for the whole app. This way, you keep all related code in a single module, which makes it very easy to maintain the project. Summary To summarise, we looked at how you can add Angular Material as a feature module in an Angular app. Although this guide is focused on the Material library, the concept can be applied to any kind of UI framework. You could, for instance, import Kendo UI dependencies through a feature module.</p>
<p>The post <a href="https://onthecode.co.uk/blog/import-angular-material-feature-module">How to Add Angular Material Components Correctly</a> appeared first on <a href="https://onthecode.co.uk">onthecode</a>.</p>
]]></description>
										<content:encoded><![CDATA[</p>
<p>In this post, I will show you how to add <a href="/blog/category/angular-material">Angular Material</a> components in an Angular application. </p>
</p>
<p>Importing UI components directly in the <code>app.module</code> increases the size of the module. The root module should be easy to maintain. Importing a button is not a great idea here.</p>
</p>
<p>For example, consider importing and configuring date picker in several feature modules. In this case, you can avoid duplication by having a single Material module.</p>
</p>
<h2 class="wp-block-heading">Add Angular Material </h2>
</p>
<p>First off, let&#8217;s add Angular Material to our project:</p>
</p>
<pre class="wp-block-code"><code>ng add @angular/material</code></pre>
</p>
<p>This command installs Angular Material, the <a href="https://material.angular.io/cdk/categories">Component Dev Kit (CDK)</a>, <a href="https://angular.io/guide/animations" target="_blank" rel="noreferrer noopener">Angular Animations</a>. </p>
</p>
<p>It will ask these questions to setup Material according to your needs:</p>
</p>
<ol class="wp-block-list">
<li>Choose a prebuilt theme name, or &#8220;custom&#8221; for a custom theme</li>
<li>Set up global Angular Material typography styles?</li>
<li>Set up browser animations for Angular Material?</li>
</ol>
</p>
<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img loading="lazy" decoding="async" src="https://onthecode.co.uk/wp-content/uploads/2022/03/Screenshot-2022-03-09-at-22.30.56-1-1024x313.png" alt="Setting up angular material" class="wp-image-4460" width="608" height="185" srcset="https://onthecode.co.uk/wp-content/uploads/2022/03/Screenshot-2022-03-09-at-22.30.56-1-1024x313.png 1024w, https://onthecode.co.uk/wp-content/uploads/2022/03/Screenshot-2022-03-09-at-22.30.56-1-300x92.png 300w, https://onthecode.co.uk/wp-content/uploads/2022/03/Screenshot-2022-03-09-at-22.30.56-1-768x234.png 768w, https://onthecode.co.uk/wp-content/uploads/2022/03/Screenshot-2022-03-09-at-22.30.56-1.png 1068w" sizes="(max-width: 608px) 100vw, 608px" /></figure>
</div>
</p>
<h2 class="wp-block-heading">Generate feature module</h2>
</p>
<p>Generate a module for keeping Material components:</p>
</p>
<pre class="wp-block-code"><code>ng generate module CustomMaterial</code></pre>
</p>
<p>This will not only create a new folder called <strong>custom-material</strong> but also a module definition for your imports.</p>
</p>
<p>Next, open up the module definition and import a button:</p>
</p>
<pre class="wp-block-code"><code>//custom-material.module.ts
import { NgModule } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
@NgModule({
  imports: &#91;
    MatButtonModule
  ],
  exports: &#91;
    MatButtonModule
  ]
})
export class CustomMaterialModule {}</code></pre>
</p>
<p>Notice we need to export the button component, which makes it available to any module that imports the <code>CustomMaterialModule</code>.</p>
</p>
<p>The idea here is that our custom material module will be responsible for any configuration, custom components etc. It should only export things that are needed by consumer modules.</p>
</p>
<p>At this point, you can import <code>CustomMaterialModule</code> in any other module.</p>
</p>
<pre class="wp-block-code"><code>@NgModule({
  declarations: &#91;
    AppComponent
  ],
  imports: &#91;
    BrowserModule,
    CustomMaterialModule,
    BrowserAnimationsModule
  ],
  providers: &#91;],
  bootstrap: &#91;AppComponent]
})
export class AppModule { }</code></pre>
</p>
<p>We can now use the button in a component:</p>
</p>
<pre class="wp-block-code"><code>&lt;button mat-raised-button&gt; Hello &lt;/button&gt;</code></pre>
</p>
<p>Going forward, you can just import the components from Angular Material into the <code>CustomMaterialModule</code> and use them in your own components. </p>
</p>
<p>For example, if you need to display icons, you need to import and export <code>MatIconModule</code> from the <code>CustomMaterialModule</code>. </p>
</p>
<h2 class="wp-block-heading">Custom components</h2>
</p>
<p>You will reap the benefits of this approach, when the time comes to implement a custom feature into any of the Material components.</p>
</p>
<p>For example, if you <a aria-label="implement a select all option for Select component (opens in a new tab)" href="https://onthecode.co.uk/implement-select-all-option-mat-select-angular-material-reactive-forms/" target="_blank" rel="noreferrer noopener">implement a select all option for Select component</a>, you can easily create a custom component inside the <code>CustomMaterialModule</code> and export it for the whole app. </p>
</p>
<p>This way, you keep all related code in a single module, which makes it very easy to maintain the project.</p>
</p>
<h2 class="wp-block-heading">Summary</h2>
</p>
<p>To summarise, we looked at how you can add Angular Material as a feature module in an Angular app. Although this guide is focused on the Material library, the concept can be applied to any kind of UI framework. You could, for instance, import Kendo UI dependencies through a feature module. </p></p>
<p>The post <a href="https://onthecode.co.uk/blog/import-angular-material-feature-module">How to Add Angular Material Components Correctly</a> appeared first on <a href="https://onthecode.co.uk">onthecode</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://onthecode.co.uk/blog/import-angular-material-feature-module/feed</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
	</channel>
</rss>
