<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Denis Lubchenko on Medium]]></title>
        <description><![CDATA[Stories by Denis Lubchenko on Medium]]></description>
        <link>https://medium.com/@rexar1988?source=rss-8491b9af9bcc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*DXlbUcxGG_E7292WZgLbLw.jpeg</url>
            <title>Stories by Denis Lubchenko on Medium</title>
            <link>https://medium.com/@rexar1988?source=rss-8491b9af9bcc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 05:31:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rexar1988/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Angular. <ng-template>, TemplateRef]]></title>
            <link>https://medium.com/@rexar1988/angular-ng-template-templateref-4bfb48e2a075?source=rss-8491b9af9bcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bfb48e2a075</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[templateref]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Denis Lubchenko]]></dc:creator>
            <pubDate>Sun, 02 Aug 2020 20:05:09 GMT</pubDate>
            <atom:updated>2020-08-02T20:05:09.831Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6qtK6V62Casrqcq26Z0JtQ.png" /></figure><p>Hi all! In this article, we will talk about another abstraction that is used for work with dynamic content — this is <a href="https://angular.io/api/core/TemplateRef"><strong>TemplateRef</strong></a>. You may also have seen the <strong><em>&lt;ng-template&gt; &lt;/ng-template&gt;</em></strong> construct on the Internet — it is the same.</p><p>The main idea of ​​using templates is as old as our world and used for a long time ago in Vanilla JavaScript. If you are familiar with the <strong><em>template </em></strong>tag that was introduced in <strong>HTML5 </strong>and how to work with it, then you won’t have any problems, <strong><em>ng-template</em></strong> works the same way only within Angular framework. Angular just provides its own template notation for content manipulation between components.</p><p>The idea behind <strong><em>ng-template</em></strong> is very simple: we create a sample HTML markup (hereinafter just an HTML template), but don’t display it until we explicitly indicate where and when to insert it. Of course, we can insert this template many times wherever we want. You may have seen this approach before if you created your own structural directives or worked with third party libraries such as <strong>Angular Material Design</strong> or <strong>NG Prime</strong>.</p><p>A simple example of <strong><em>ng-template</em></strong> in a component template:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b77ef9d3f28bb81386729c97a20c7060/href">https://medium.com/media/b77ef9d3f28bb81386729c97a20c7060/href</a></iframe><p>If you add the code above to your Angular component view template, you will find that the HTML wrapped in the <strong><em>ng-template</em></strong> tag and is not visually visible and doesn’t appear in the DOM tree. But if you open the console and take a look at the HTML inspector, we will see that Angular has inserted a certain DOM comment node <strong><em>&lt;!-- container --&gt;</em></strong><em>.</em> We will return to it a bit later.</p><p>An instance of the TemplateRef class contains the following properties and methods:</p><ul><li><a href="https://angular.io/api/core/TemplateRef#elementRef"><strong>ElementRef</strong></a><strong> </strong>— A read only property that returns the HTML element where our <strong><em>ng-template</em></strong> is located in the DOM tree. In our case, this is the same comment <strong><em>&lt;!--container--&gt;</em></strong>, with which we can access this template;</li><li><a href="https://angular.io/api/core/TemplateRef#createEmbeddedView"><strong>createEmbeddedView(context: C): EmbeddedViewRef&lt;C&gt;</strong></a><strong> </strong>— a method that allows to create views and return a reference as a type <a href="https://angular.io/api/core/ViewRef"><strong>ViewRef</strong></a>. It may be needed in in bundle with the <a href="https://angular.io/api/core/ViewContainerRef"><strong>ViewContainerRef </strong></a>method.</li></ul><h3>Directive ngTemplateOutlet</h3><p>We figured out how to create templates using the <strong><em>ng-template</em></strong> tag, so it’s time to learn how to display these templates. Let’s create the following template and display it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/90cd19ab7878003c59b1660c06150c33/href">https://medium.com/media/90cd19ab7878003c59b1660c06150c33/href</a></iframe><p>To insert a template, the <a href="https://angular.io/api/common/NgTemplateOutlet"><strong>ngTemplateOutlet </strong></a>directive is used, which takes the <strong>TemplateRef </strong>type as a parameter. I specially inserted this template three times to show that we can insert it as many times as we want.</p><p>Of course, on practice, this doesn’t make sense, but in order to show how it works, I chose the simplest example. I’ll write another article about content projection between components using <strong>TemplateRef </strong>and other abstractions, everything has its time 😉.</p><h3>Context</h3><p>However, this article doesn’t end 😎, further we will talk about another important concept of <strong>Context</strong>, with which a template can interact with the component in which it is rendered.</p><p>I hope you are already familiar with the micro-syntax of structural directives, if not, then you need to go <a href="https://angular.io/guide/structural-directives#microsyntax">here</a>. So, using the <strong>let-*</strong> syntax, you can create variables inside the <strong><em>&lt;ng-template&gt;</em></strong> template.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae09686d0fcd6918eb50e27288c06971/href">https://medium.com/media/ae09686d0fcd6918eb50e27288c06971/href</a></iframe><p>From the example above, you can see that we create the <strong>firstName </strong>variable using the keyword <strong>let</strong> and display this variable in the <strong><em>p</em></strong> tag. You can see also that the variable <strong>firstName </strong>is assigned <strong>myFirstName </strong>value. Now arises a logical question: <em>“Where to get the data?”</em> Everything is very simple: to pass data for the specified variables, we must pass a context object that will contain the corresponding properties, in our case these are <strong>myFirstName </strong>and <strong>greeting</strong>. Let’s create a <strong>context </strong>variable in our component and add the necessary properties there:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c68ddb4143888f2ddb325989bcf70fc/href">https://medium.com/media/3c68ddb4143888f2ddb325989bcf70fc/href</a></iframe><h4>Directive ngTemplateOutletContext</h4><p>The <a href="https://angular.io/api/common/NgTemplateOutlet"><strong>ngTemplateOutletContext </strong></a>directive is used for pass the context as a data provider for the template. Let’s take a look on example below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c13e82f12ba14d0944095910fe480079/href">https://medium.com/media/c13e82f12ba14d0944095910fe480079/href</a></iframe><p>I deliberately made different variable names in <strong>firstName </strong>and <strong>myFirstName </strong>to show that it is not necessary to give the same name to bind. The variable in <strong>ng-template</strong> and the context property must be bound. You might mistakenly think that if we write like this:</p><pre>&lt;ng-template let-<strong><em>firstName</em></strong>&gt;<br>  &lt;div&gt;{{ <strong><em>firstName </em></strong>}}&lt;/div&gt;<br>&lt;/ng-template&gt;</pre><p>and then by creating a <strong>firstName </strong>property in the context object, then this will work:</p><pre>context = {<br>  <strong>firstName</strong>: &#39;John Doe&#39;,<br>};</pre><p><strong>But no! This won’t work!</strong></p><p>In summary, the context is a kind of link between the template and the component in which the template is displayed.</p><p>In general, that’s all, but to finally add up the whole picture, let’s look at a complete example.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fangular-ng-template-context%3Fembed%3D1&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fangular-ng-template-context&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-03bbb9acbba813917725387f46e5df03a95d232be240e910ce5f946a973b3f86.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b0627ebefa7dbc7b135bca0f9addf1d/href">https://medium.com/media/3b0627ebefa7dbc7b135bca0f9addf1d/href</a></iframe><h3>Property $implicit</h3><p>In context object, we can have the key property <strong>$implicit</strong>. It can be used to set the default value for all variables whose values are not set.</p><pre>context = {<br>  <strong>$implicit</strong>: &#39;Default Value&#39;<br>};</pre><p>The following templates are the same:</p><pre>&lt;ng-template let-<strong><em>firstName </em></strong><em>let-</em><strong><em>secondName</em></strong>&gt;<br>  &lt;div&gt;{{ <strong><em>firstName </em></strong>}}&lt;/div&gt;<br>  &lt;div&gt;{{ <strong><em>secondName </em></strong>}}&lt;/div&gt;<br>&lt;/ng-template&gt;</pre><pre>&lt;ng-template let-<strong><em>firstName=</em></strong><em>&quot;$implicit&quot;</em><strong><em> </em></strong>let-<strong><em>secondName</em></strong><em>=&quot;$implicit&quot;</em>&gt;<br>  &lt;div&gt;{{ <strong><em>firstName </em></strong>}}&lt;/div&gt;<br>  &lt;div&gt;{{ <strong><em>secondName </em></strong>}}&lt;/div&gt;<br>&lt;/ng-template&gt;</pre><p>Angular will substitute the <strong>$implicit</strong> property for us in variables whose values are not set, which means that in both cases will be displayed — <strong>Default Value</strong>.</p><h3>Ideology of approach with templates</h3><p>At the end of this article, I would like to summarize everything that we have gone through and try to clearly explain when all this can be useful to us. I think that there should be no questions about why you need to pass content from component to another component, and in general that you can define an HTML template and use it several times also. However, when we to have a possibility to use variables and methods there, and at this point I would like to stop and consider it in details.</p><p>Since we can define and use variables inside the <strong>ng-template</strong>, this means that we need to get the values ​​for these variables somewhere. From the template, we can access the properties and methods of the component in which this template is applied directly through the <strong>context</strong>. Thus, in our <strong>ng-template</strong> is stored roughly speaking the sketch, but the implementation of this sketch is in the components themselves and, accordingly, this implementation is likely to be different for each component. In the following example, we are using the <strong>ng-template</strong> in several components, but as we will see later, each component will have its own implementation for this template.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fng-template-implementation%3Fembed%3D1&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fng-template-implementation&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-03bbb9acbba813917725387f46e5df03a95d232be240e910ce5f946a973b3f86.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/7abd5c245af58ecb747a08eda759e100/href">https://medium.com/media/7abd5c245af58ecb747a08eda759e100/href</a></iframe><h3>Conclusion</h3><p>In this article, we covered a very important abstraction for working with dynamic content.</p><ul><li><strong>ng-template</strong> and <strong>TemplateRef </strong>are the same;</li><li>All HTML markup placed in the <strong><em>&lt;ng-template&gt;&lt;/ng-template&gt;</em></strong> tag will not be displayed until we explicitly indicate where and when to display it;</li><li>The <strong>ngTemplateOutlet </strong>directive inserts the content of the <strong>ng-template</strong> into the HTML element on which the directive is applied;</li><li>Within the template, you can use variables and methods, the values ​​of which can be passed using the context;</li><li>You can pass the context using the <strong>ngTemplateOutletContext </strong>directive;</li><li>The <strong>$implicit</strong> property sets default values ​​for variables with no value;</li><li>The template approach is useful if you need to have a structure of HTML markup, but implementation may differ from component to component.</li></ul><p>And actually on this I want to end this article! If you have any questions, write in the comments. See you soon!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bfb48e2a075" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular. <ng-template>, TemplateRef (RUS)]]></title>
            <link>https://medium.com/@rexar1988/angular-ng-template-templateref-f6aaca0548e3?source=rss-8491b9af9bcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6aaca0548e3</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[templateref]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Denis Lubchenko]]></dc:creator>
            <pubDate>Sat, 01 Aug 2020 21:46:40 GMT</pubDate>
            <atom:updated>2020-08-02T20:06:10.566Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6qtK6V62Casrqcq26Z0JtQ.png" /></figure><p>Всем привет! В этой статье мы поговорим еще про одну абстракцию, которая используется для работы с динамическим контентом — это <a href="https://angular.io/api/core/TemplateRef"><strong>TemplateRef</strong></a>. Вы также могли встречать конструкцию <strong><em>&lt;ng-template&gt;&lt;/ng-template&gt;</em></strong> — это одно и то же.</p><p>Сама идея применения шаблонов старая как наш мир и уже давно используется в обычном JavaScript. Если вы знакомы с тегом <strong>template </strong>который появился в <strong>HTML5 </strong>и особенностями работы с ним, то <strong>ng-template</strong> работает аналогично только в рамках Angular. Angular просто предоставляет свою нотацию шаблонов для манипуляции контентом.</p><p>Идея <strong>ng-template</strong> очень простая: мы создаем образец разметки HTML кода (далее просто HTML-шаблон), но не отображаем его до тех пор, пока явно не укажем куда и когда его вставлять. Вставить этот шаблон мы конечно же можем множество раз куда захотим. Вы могли видеть этот подход раньше если создавали свои структурные директивы или работали со сторонними библиотеками такими как <strong>Angular Material Design</strong> или <strong>NG Prime</strong>.</p><p>Простой пример <strong>ng-template</strong> в шаблоне компонента:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b77ef9d3f28bb81386729c97a20c7060/href">https://medium.com/media/b77ef9d3f28bb81386729c97a20c7060/href</a></iframe><p>Если вы добавите код выше в шаблон Angular компонента, то обнаружите что HTML обернутый в тег <strong>ng-template</strong> не виден визуально и не отображается в DOM-дереве. Но открыв консоль и посмотрев в инспектор HTML кода, мы увидим, что Angular вставил некий DOM-узел комментария <strong><em>&lt;!--container--&gt;</em></strong><em>.</em> К нему мы вернемся чуть позже.</p><p>Экземпляр класса <strong>TemplateRef </strong>содержит следующие свойства и методы:</p><ul><li><a href="https://angular.io/api/core/TemplateRef#elementRef"><strong>ElementRef </strong></a>— свойство для чтения, которое возвращает HTML-элемент, где расположен наш <strong>ng-template</strong><em> </em>в DOM-дереве. В нашем случае это тот самый комментарий <strong><em>&lt;!--container --&gt;</em></strong>, с помощью которого мы можем получить доступ к данному шаблону;</li><li><a href="https://angular.io/api/core/TemplateRef#createEmbeddedView"><strong>createEmbeddedView(context: C): EmbeddedViewRef&lt;C&gt;</strong></a><strong> </strong>— метод, который позволяет создавать представления и возвращать на них ссылку типа <a href="https://angular.io/api/core/ViewRef"><strong>ViewRef</strong></a>. Он может понадобиться в связке с методом <a href="https://angular.io/api/core/ViewContainerRef"><strong>ViewContainerRef</strong></a><strong> </strong>о котором вы можете почитать в этой <a href="https://medium.com/@rexar1988/angular-%D0%B4%D0%B8%D0%BD%D0%B0%D0%BC%D0%B8%D1%87%D0%B5%D1%81%D0%BA%D0%B8%D0%B9-%D0%BA%D0%BE%D0%BD%D1%82%D0%B5%D0%BD%D1%82-%D1%87%D0%B0%D1%81%D1%82%D1%8C-1-viewcontainerref-b7463f66c75d">статье</a>.</li></ul><h3><strong>Директива ngTemplateOutlet</strong></h3><p>Мы разобрались как создавать шаблоны с помощью тега <strong><em>ng-template</em></strong>, соответственно пришло время научиться отображать эти шаблоны. Давайте создадим следующий простой шаблон и сразу выведем его.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/90cd19ab7878003c59b1660c06150c33/href">https://medium.com/media/90cd19ab7878003c59b1660c06150c33/href</a></iframe><p>Для вставки шаблона используется директива <a href="https://angular.io/api/common/NgTemplateOutlet"><strong>ngTemplateOutlet</strong></a>, которая в качестве параметра принимает тип <strong>TemplateRef</strong>. Я специально вставил три раза этот шаблон, чтобы показать что мы можем его вставлять сколько угодно раз.</p><p>Конечно на практике скорей всего это не имеет никакого смысла, но для того чтобы показать, как это работает я выбрал самый простой вариант для примера. О том, как проецировать контент между компонентами применяя <strong>TemplateRef</strong> и другие абстракции, я напишу отдельную статью, всему свое время 😉.</p><h3>Контекст</h3><p>Однако на этом статья не заканчивается 😎, дальше мы поговорим о ещё одной важной концепции <strong>Контекста</strong>, с помощью которого шаблон может взаимодействовать с компонентом в котором он выводиться.</p><p>Я надеюсь вы уже знакомы с микро-синтаксисом структурных директив, если нет, тогда вам нужно с ним ознакомиться <a href="https://angular.io/guide/structural-directives#microsyntax">здесь</a>. Так вот, с помощью синтаксиса <strong>let-*</strong> можно создавать переменные внутри шаблона <strong><em>&lt;ng-template&gt;</em></strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae09686d0fcd6918eb50e27288c06971/href">https://medium.com/media/ae09686d0fcd6918eb50e27288c06971/href</a></iframe><p>Из примера выше видно, что мы создаем переменную <strong>firstName </strong>с помощью слова <strong>let </strong>и выводим эту переменную в теге <strong><em>p</em></strong>. Также бросается в глаза, что переменной <strong>firstName </strong>присваивается значение <strong>myFirstName</strong>. Теперь возникает закономерный вопрос: <em>“Откуда брать данные?”</em> Всё очень просто: чтобы передать данные для указанных переменных мы должны передать объект контекста, в котором будут содержатся соответствующие свойства, в нашем случае это <strong>myFirstName </strong>и<em> </em><strong>greeting</strong><em>. </em>Давайте заведем переменную <strong>context</strong> в нашем компоненте и добавим туда необходимые свойства:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c68ddb4143888f2ddb325989bcf70fc/href">https://medium.com/media/3c68ddb4143888f2ddb325989bcf70fc/href</a></iframe><h4><strong>Директива ngTemplateOutletContext</strong></h4><p>Чтобы передать контекст в качестве поставщика данных для шаблона, используется директива <strong>ngTemplateOutletContext</strong>. Давайте посмотрим пример ниже:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c13e82f12ba14d0944095910fe480079/href">https://medium.com/media/c13e82f12ba14d0944095910fe480079/href</a></iframe><p>Я специально сделал разные имена переменных в <strong>firstName </strong>и <strong>myFirstName</strong>, чтобы показать, что необязательно давать одинаковые имена для связывания. Переменную в <strong>ng-template</strong> и свойство контекста обязательно нужно связать. Ошибочно можно подумать, что если мы напишем так:</p><pre>&lt;ng-template let-<strong><em>firstName</em></strong>&gt;<br>  &lt;div&gt;{{ <strong><em>firstName </em></strong>}}&lt;/div&gt;<br>&lt;/ng-template&gt;</pre><p>а затем создав свойство <strong><em>firstName </em></strong>в объекте контекста, то это будет работать:</p><pre>context = {<br>  <strong>firstName</strong>: &#39;John Doe&#39;,<br>};</pre><p><strong>Но это не так! Так работать не будет!</strong></p><p>Если подвести такой итог, то контекст является неким связующим звеном между шаблоном и компонентом в котором выводиться шаблон.</p><p>В общем собственно и всё, но, чтобы окончательно сложить всю картину, давайте посмотрим на полный пример.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fangular-ng-template-context%3Fembed%3D1&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fangular-ng-template-context&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-03bbb9acbba813917725387f46e5df03a95d232be240e910ce5f946a973b3f86.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b0627ebefa7dbc7b135bca0f9addf1d/href">https://medium.com/media/3b0627ebefa7dbc7b135bca0f9addf1d/href</a></iframe><h3><strong>Свойство $implicit</strong></h3><p>В контексте у нас может быть ключевое свойство <strong>$implicit</strong>. С его помощью можно устанавливать значение по умолчанию для всех переменных значения которых не заданы.</p><pre>context = {<br>  <strong>$implicit</strong>: &#39;Default Value&#39;<br>};</pre><p>Следующие записи идентичны:</p><pre>&lt;ng-template let-<strong><em>firstName </em></strong><em>let-</em><strong><em>secondName</em></strong>&gt;<br>  &lt;div&gt;{{ <strong><em>firstName </em></strong>}}&lt;/div&gt;<br>  &lt;div&gt;{{ <strong><em>secondName </em></strong>}}&lt;/div&gt;<br>&lt;/ng-template&gt;</pre><pre>&lt;ng-template let-<strong><em>firstName=</em></strong><em>&quot;$implicit&quot;</em><strong><em> </em></strong>let-<strong><em>secondName</em></strong><em>=&quot;$implicit&quot;</em>&gt;<br>  &lt;div&gt;{{ <strong><em>firstName </em></strong>}}&lt;/div&gt;<br>  &lt;div&gt;{{ <strong><em>secondName </em></strong>}}&lt;/div&gt;<br>&lt;/ng-template&gt;</pre><p>Angular за нас подставит свойство <strong>$implicit</strong> в переменные, значения которых не заданны, это значит, что в обоих случаях выведется <strong>Default Value.</strong></p><h3>Идеология подхода с шаблонами</h3><p>В конце данной статьи я хотел бы подвести итог всего того, что мы прошли и попытаться доходчиво объяснить, когда все это нам может пригодиться. Я думаю, что вопросов зачем нужно передавать контент от компонента к компоненту быть не должно, и в общем что можно определить HTML-шаблон и использовать его несколько раз тоже. Однако, когда у нас появляется возможность использовать там еще переменные и методы, и вот на этом моменте я хотел бы остановиться и рассмотреть это чуть подробнее.</p><p>Поскольку мы можем определять и использовать переменные внутри шаблона <strong>ng-template</strong>, это значит, что нам нужно где-то брать значения для этих переменных. Из шаблона мы можем обращаться к свойствам и методам компонента в котором применяется этот шаблон непосредственно через связующее звено, которым является <strong>контекст</strong>. Таким образом у нас в шаблоне <strong>ng-template</strong> храниться грубо, говоря макет, а вот реализация этого макета находиться в самих компонентах и соответственно эта реализация скорей всего у каждого компонента будет своя. В следующем примере мы используем <strong><em>ng-template</em></strong> шаблон в нескольких компонентах, но как мы увидим дальше, реализация для этого шаблона у каждого компонента будет своя.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fng-template-implementation%3Fembed%3D1&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fng-template-implementation&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-03bbb9acbba813917725387f46e5df03a95d232be240e910ce5f946a973b3f86.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/7abd5c245af58ecb747a08eda759e100/href">https://medium.com/media/7abd5c245af58ecb747a08eda759e100/href</a></iframe><h3><strong>Заключение</strong></h3><p>В этой статье мы рассмотрели очень важную абстракцию для работы с динамическим контентом.</p><ul><li><strong>ng-template</strong> и <strong>TemplateRef </strong>одно и то же;</li><li>Вся HTML-разметка заключенная в тег <strong><em>&lt;ng-template&gt;&lt;/ng-template&gt;</em></strong><em> </em>не будет отображаться до тех пор пока мы явно не укажем, куда и когда её выводить;</li><li>Директива <strong>ngTemplateOutlet </strong>вставляет содержимое шаблона <strong>ng-template</strong> в HTML-элемент, на котором применена директива;</li><li>Внутри шаблона можно использовать переменные и методы, значения которых можно передавать с помощью контекста;</li><li>Передавать контекст можно с помощью директивы <strong>ngTemplateOutletContext</strong>;</li><li>Свойство <strong>$implicit</strong> задает значения по умолчанию для переменных без значения;</li><li>Подход с шаблонами удобен если нужно иметь четкую структуру HTML-разметки, но реализация может отличаться в разных компонентах.</li></ul><p>И собственно на этом я хочу закончить данную статью! Если остались вопросы — пишите в комментариях. До скорых встреч!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6aaca0548e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular. Динамический контент, часть 1: ViewContainerRef]]></title>
            <link>https://medium.com/@rexar1988/angular-%D0%B4%D0%B8%D0%BD%D0%B0%D0%BC%D0%B8%D1%87%D0%B5%D1%81%D0%BA%D0%B8%D0%B9-%D0%BA%D0%BE%D0%BD%D1%82%D0%B5%D0%BD%D1%82-%D1%87%D0%B0%D1%81%D1%82%D1%8C-1-viewcontainerref-b7463f66c75d?source=rss-8491b9af9bcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7463f66c75d</guid>
            <category><![CDATA[html]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Denis Lubchenko]]></dc:creator>
            <pubDate>Thu, 30 Jul 2020 21:08:27 GMT</pubDate>
            <atom:updated>2020-08-01T00:24:06.050Z</atom:updated>
            <content:encoded><![CDATA[<h3>Angular. Динамический контент. Часть 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WPLopv3XaweoMo0_D6feqg.png" /></figure><p>Очень редко, когда проект может обойтись без динамического создания элементов, рано или поздно придется задуматься о создании модальных окон, всплывающих подсказок или же просто передавать данные от компонента к компоненту. Если вы задавали себе вопрос <em>«как в Angular можно отображать контент динамически?»</em>, тогда вам сюда! 😎</p><p>Когда я начал искать ответ на данный вопрос, поиск привел меня к ряду абстракций, но все эти абстракции крутилось вокруг класса <a href="https://angular.io/api/core/ViewContainerRef"><strong><em>ViewContainerRef</em></strong></a><strong><em>, </em></strong>с него мы и начнем. После я решил почитать об этом подробнее в официальной документации по Angular и увидел там следующее описание:</p><blockquote>Represents a container where one or more views can be attached to a component.</blockquote><p>И это все, что там написано 😥, как-то не очень информативно подумал я и понял что тема <strong>Динамического контента</strong> плохо раскрыта, так я решил написать серию статей по данной теме. Я надеюсь, что это будет последняя статья о <strong><em>ViewContainerRef</em></strong>, которая вам когда-либо понадобиться 😀.</p><p>Давайте сначала вернемся в обычный <strong>JavaScript</strong> и вспомним как мы можем динамически вставить один DOM-элемент после другого.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b9892e11cd7b7f435d1177e17c79bdf/href">https://medium.com/media/9b9892e11cd7b7f435d1177e17c79bdf/href</a></iframe><p>Отлично, если вы запустите пример выше, то увидите, как элемент с классом .<strong><em>element </em></strong>будет вставлен после элемента с классом .<strong><em>parent-element</em></strong>. Из этого примера следует:</p><p>1. Нам нужен DOM-элемент для вставки;</p><p>2. Нам также нужен DOM-элемент, который будет являться контейнером, внутрь которого мы будем вставлять этот элемент.</p><p>Angular не является чем-то сверхъестественным и это по-прежнему тот же JavaScript, соответственно если вы хотите вставить DOM-элемент (компонент или кусок HTML-шаблона) вам нужен контейнер для вставки этого элемента.</p><p>За динамическую генерацию контента в Angular, отвечает сервис <strong><em>ViewContainerRef. </em></strong>Далее будет очень <strong>важное определение</strong>, об этом сервисе, постарайтесь это понять и запомнить и тогда у вас больше не будет возникать вопросов, что такое <strong><em>ViewContainerRef</em></strong>:</p><blockquote><strong>ViewContainerRef </strong>— это ссылка на DOM-элемент, который является контейнером для динамической вставки компонента или HTML-шаблона. Вставленные компоненты и HTML-шаблоны будут являться дочерними по отношению к этому контейнеру.</blockquote><p>Название класса говорит само за себя:</p><p>1. <strong>View </strong>— шаблон. В нашем случае тот шаблон компонента или DOM-элемент директивы в которой был внедрен сервис <strong><em>ViewContainerRef</em></strong>;</p><p>2. <strong>Container </strong>— Контейнер. Собственно, контейнер для вставки о котором мы говорили ранее;</p><p>3. <strong>Ref </strong>— Сокращение от <em>Reference </em>или просто ссылка.</p><p>Итого у нас и получается <strong><em>ViewContainerRef </em></strong>— Ссылка на шаблон контейнера.</p><p>Если привести аналогию с примером выше, то <strong><em>ViewContainerRef — </em></strong><em>это .parent-element</em> в который будет вставлен динамический контент.</p><h3>ViewContainerRef и Dependency Injection</h3><p>Первое что нужно сделать это внедрить <strong><em>ViewContainerRef </em></strong>с помощью <strong><em>Dependency Injection</em></strong> в компонент или директиву. Контейнером для вставки динамического контента будет являться HTML-шаблон компонента если мы внедрили этот сервис в компонент или DOM-элемент если это директива.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f66317d3648dcfb2d61e5492d13e85e2/href">https://medium.com/media/f66317d3648dcfb2d61e5492d13e85e2/href</a></iframe><p>Теперь давайте посмотрим, что из себя представляет <strong><em>ViewContainerRef </em></strong>в консоле. Для примера я создал компонент <em>app-node-type-list</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22007cc7ab7424cb2668d300f959c754/href">https://medium.com/media/22007cc7ab7424cb2668d300f959c754/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W8T7skorW_RXhclyCp_WBA.png" /><figcaption><strong>ViewContainerRef </strong>внедренный в компонент</figcaption></figure><p>Если обратить внимание на свойство <strong><em>nativeElement</em></strong>, то мы увидим, что это HTML-шаблон (он же host-элемент) компонента в котором произошло внедрение <strong><em>ViewContainerRef</em></strong>.</p><p>Ниже давайте посмотрим на вывод в консоль, если мы сделаем тоже самое для какой-нибудь директивы.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TFTxp2L_qcLZB5W3RUQXuw.png" /><figcaption><strong>ViewContainerRef </strong>внедренный в директиву</figcaption></figure><p>Angular добавляет в DOM-дерево комментарий &lt;!--container → (закрывающий тег не получился, medium что ты творишь 🤣) перед которым вставляет весь динамический контент.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*SU5c87NS1z9f35uOVAHoEA.png" /><figcaption>Колонки таблицы <strong>tr</strong> были добавлены динамически</figcaption></figure><p>Ну вот и все! Ничего сложного, согласитесь? Только что мы посмотрели, как отображается динамически вставленные элементы в Angular и наш следующий этап — это разобраться как манипулировать динамическим контентом.</p><h3>Заключение</h3><p>В этой статье мы разобрали, что такое <strong><em>ViewContainerRef </em></strong>и для чего он нужен.</p><ul><li><strong><em>ViewContainerRef </em></strong>— это ссылка на контейнер где был внедрен данный сервис;</li><li>Если <strong>ViewContainerRef </strong>был внедрен в компонент — тогда это будет host-элемент компонента, то есть его HTML-шаблон;</li><li>Для директивы, это будет HTML-элемент, на который была применена директива.</li></ul><p>На самом деле именно на этой ноте я и хотел бы закончить данную статью, чтобы вы смогли устаканить всю полученную информацию.</p><p>Пока что мы так и не научились манипулировать динамическим контентом с помощью этого сервиса, об этом мы уже поговорим в следующей статье.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7463f66c75d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>