<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Stack Overflow - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Stack Overflow - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Fri, 26 Jun 2026 22:47:50 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/stackoverflow/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ The Most Asked TypeScript Questions on StackOverflow – Handbook for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ By Emmanuel Ohans _"I hate stack overflow"_ — said no developer ever. While it’s helpful to have your answers a Google search away, what’s even more powerful is truly understanding the solutions you stumble upon. In this article, I’ll explore the sev... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/the-top-stack-overflowed-typescript-questions-explained/</link>
                <guid isPermaLink="false">66d45e613a8352b6c5a2aa36</guid>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Stack Overflow ]]>
                    </category>
                
                    <category>
                        <![CDATA[ TypeScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 11 Jul 2022 15:52:33 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/07/combined-blog-cover-6.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Emmanuel Ohans</p>
<p>_"<em>I hate stack overflow</em>"_ — said no developer ever.</p>
<p>While it’s helpful to have your answers a Google search away, what’s even more powerful is truly understanding the solutions you stumble upon.</p>
<p>In this article, I’ll explore the seven most <em>stackoverflowed</em> TypeScript questions.</p>
<p>I spent hours researching these.</p>
<p>I hope you gain a deeper understanding of the common problems you may face with TypeScript.</p>
<p>This is also relevant if you’re just learning TypeScript — what better way than to get familiar with your future challenges!</p>
<p>Let’s get right into it.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><a class="post-section-overview" href="#heading-1-what-is-the-difference-between-interfaces-vs-types-in-typescript">What is the difference between Interfaces vs Types in TypeScript?</a></li>
<li><a class="post-section-overview" href="#2-in-typescript-what-is-the-exclamation-mark-bang-operator">In TypeScript, what is the ! (exclamation mark / bang) operator?</a></li>
<li><a class="post-section-overview" href="#3-what-is-a-d-ts-file-in-typescript">What is a “.d.ts” file in TypeScript?</a></li>
<li><a class="post-section-overview" href="#4-how-do-you-explicitly-set-a-new-property-on-window-in-typescript">How Do You Explicitly Set a New Property on ‘window’ in TypeScript?</a></li>
<li><a class="post-section-overview" href="#5-are-strongly-typed-functions-as-parameters-possible-in-typescript">Are Strongly Typed Functions as Parameters Possible in TypeScript?</a></li>
<li><a class="post-section-overview" href="#6-how-to-fix-could-not-find-declaration-file-for-module-">How to Fix Could Not Find Declaration File for Module …?</a></li>
<li><a class="post-section-overview" href="#7-how-do-i-dynamically-assign-properties-to-an-object-in-typescript">How Do I Dynamically Assign Properties to an Object in TypeScript?</a></li>
</ol>
<p><strong>Note:</strong> You can get a <a target="_blank" href="https://www.ohansemmanuel.com/cheatsheet/top-7-stack-overflowed-typescript-questions">PDF or ePub</a> version of this cheatsheet for easier reference or for reading on your Kindle or tablet.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/image-51.png" alt="Image" width="600" height="400" loading="lazy">
<em><a target="_blank" href="https://www.ohansemmanuel.com/cheatsheet/top-7-stack-overflowed-typescript-questions">PDF or Epub version of this cheatsheet available</a></em></p>
<h1 id="heading-1-what-is-the-difference-between-interfaces-vs-types-in-typescript">1. What is the difference between Interfaces vs Types in TypeScript?</h1>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/image-52.png" alt="Image" width="600" height="400" loading="lazy">
<em>Interfaces vs Types in Typescript</em></p>
<p>The interfaces vs types (technically, type alias) conversation is a well-contested one.</p>
<p>When beginning TypeScript, you may find it confusing to settle on a choice. This article clears up the confusion and helps you choose which is right for you.</p>
<h2 id="heading-tldr">TL;DR</h2>
<p>In numerous instances, you can use either an interface or type alias interchangeably.</p>
<p>Almost all features of an interface are available via type aliases, except you cannot add new properties to a type by re-declaring it. You must use an intersection type.</p>
<h2 id="heading-why-the-confusion-about-types-vs-interfaces-in-the-first-place">Why the Confusion About Types vs Interfaces in the First Place?</h2>
<p>Whenever we’re faced with multiple options, most people begin to suffer from the <a target="_blank" href="https://en.wikipedia.org/wiki/The_Paradox_of_Choice">paradox of choice</a>.</p>
<p>In this case, there are just two options.</p>
<p>What’s so confusing about this?</p>
<p>Well, the main confusion here stems from the fact that these two options are so <strong>evenly matched</strong> in most regards.</p>
<p>This makes it difficult to make an obvious choice — especially if you’re just starting out with Typescript.</p>
<h2 id="heading-a-basic-example-of-type-alias-vs-interface">A Basic Example of Type Alias vs Interface</h2>
<p>Let’s get on the same page with quick examples of an interface and a type alias.</p>
<p>Consider the representations of a <code>Human</code> type below:</p>
<pre><code class="lang-ts"><span class="hljs-comment">// type </span>
<span class="hljs-keyword">type</span> Human = {
  name: <span class="hljs-built_in">string</span> 
  legs: <span class="hljs-built_in">number</span> 
  head: <span class="hljs-built_in">number</span>
}

<span class="hljs-comment">// interface </span>
<span class="hljs-keyword">interface</span> Human {
  name: <span class="hljs-built_in">string</span> 
  legs: <span class="hljs-built_in">number</span> 
  head: <span class="hljs-built_in">number</span>
}
</code></pre>
<p>These are both correct ways to denote the <code>Human</code> type – that is via a type alias or an interface.</p>
<h2 id="heading-the-differences-between-type-alias-and-interfaces">The Differences Between Type Alias and Interfaces</h2>
<p>Below are the main differences between a type alias and an interface:</p>
<h3 id="heading-key-difference-interfaces-can-only-describe-object-shapes-type-aliases-can-be-used-for-other-types-such-as-primitives-unions-and-tuples">Key difference: interfaces can only describe object shapes. Type aliases can be used for other types such as primitives, unions and tuples.</h3>
<p>A type alias is quite flexible in the data types you can represent. From basic primitives to complex unions and tuples, as shown below:</p>
<pre><code class="lang-ts"><span class="hljs-comment">// primitives </span>
<span class="hljs-keyword">type</span> Name = <span class="hljs-built_in">string</span> 

<span class="hljs-comment">// object </span>
<span class="hljs-keyword">type</span> Male = {
  name: <span class="hljs-built_in">string</span>
}

<span class="hljs-keyword">type</span> Female = {
  name: <span class="hljs-built_in">string</span> 
}

<span class="hljs-comment">// union</span>
<span class="hljs-keyword">type</span> HumanSex = Male | Female

<span class="hljs-comment">// tuple</span>
<span class="hljs-keyword">type</span> Children = [Female, Male, Female]
</code></pre>
<p>Unlike type aliases, you may only represent object types with an interface.</p>
<h3 id="heading-key-difference-an-interface-can-be-extended-by-declaring-it-multiple-times">Key difference: an interface can be extended by declaring it multiple times</h3>
<p>Consider the following example:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">interface</span> Human {
  name: <span class="hljs-built_in">string</span> 
}

<span class="hljs-keyword">interface</span> Human {
  legs: <span class="hljs-built_in">number</span> 
}
</code></pre>
<p>The two declarations above will become:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">interface</span> Human {
  name: <span class="hljs-built_in">string</span> 
  legs: <span class="hljs-built_in">number</span> 
}
</code></pre>
<p><code>Human</code> will be treated as a single interface: a combination of the members of both declarations.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/image-53.png" alt="Image" width="600" height="400" loading="lazy">
<em>Property 'legs' is required in type 'Humans'</em></p>
<p>See <a target="_blank" href="https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgBIFcC2cTIN4BQyxyIcmEAXMgM5hSgDmBAvgaJLIihtroSWQAbCIxrUQWAEbRWBAgHoFyMAAtgNZNCgB7KJp3owyGQjjoaKAOQixV5JgvGIADw3GCCHSDrJV1XhxkAF58IhIyCmorAHlVHE0AUUw+dAghK1YgA">TypeScript playground</a>.</p>
<p>This is not the case with type aliases.</p>
<p>With a type alias, the following will lead to an error:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">type</span> Human = {
    name: <span class="hljs-built_in">string</span> 
}

<span class="hljs-keyword">type</span> Human =  {
    legs: <span class="hljs-built_in">number</span> 
}

<span class="hljs-keyword">const</span> h: Human = {
   name: <span class="hljs-string">'gg'</span>,
   legs: <span class="hljs-number">5</span> 
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/image-54.png" alt="Image" width="600" height="400" loading="lazy">
<em>Duplicate identifier 'Human' error</em></p>
<p>See the <a target="_blank" href="https://www.typescriptlang.org/play?#code/C4TwDgpgBAEgrgWwIYDsoF4oG8BQV9QpIIQBcUAzsAE4CWKA5lDgL57OiSyKob64EoAGwgMK5FIgBGEaszY4AxgHsUVKAAty8ZGkwD8REuQDkDBiYA07YaPFQArPPw5XroA">TypeScript playground</a>.</p>
<p>With type aliases, you’ll have to resort to an intersection type:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">type</span> HumanWithName = {
    name: <span class="hljs-built_in">string</span> 
}

<span class="hljs-keyword">type</span> HumanWithLegs =  {
    legs: <span class="hljs-built_in">number</span> 
}

<span class="hljs-keyword">type</span> Human  = HumanWithName &amp; HumanWithLegs

<span class="hljs-keyword">const</span> h: Human = {
   name: <span class="hljs-string">'gg'</span>,
   legs: <span class="hljs-number">5</span> 
}
</code></pre>
<p>See the <a target="_blank" href="https://www.typescriptlang.org/play?#code/C4TwDgpgBAEgrgWwIYDsDqBLYALAckhaAXigG8AoKKqFAiALigGdgAnDFAcynIF9KeoSLESpMOADIROTKCTICqAG2lNGKRACMIrHv3JDo8ZCioljYrHjpQAZCJPjsUmeXIBjAPYoWUbIwtTEgpqWkJGAHJOTgiAGkUVGUYAVj0qNwygA">TypeScript playground</a>.</p>
<h3 id="heading-minor-difference-both-type-aliases-and-interfaces-can-be-extended-but-with-different-syntaxes">Minor difference: Both type aliases and interfaces can be extended, but with different syntaxes</h3>
<p>With interfaces, you use the <code>extends</code> keyword. For types, you must use an intersection.</p>
<p>Consider the following examples:</p>
<h4 id="heading-type-alias-extends-a-type-alias">Type alias extends a type alias</h4>
<pre><code class="lang-ts">
<span class="hljs-keyword">type</span> HumanWithName = {
  name: <span class="hljs-built_in">string</span> 
}

<span class="hljs-keyword">type</span> Human = HumanWithName &amp; {
   legs: <span class="hljs-built_in">number</span> 
   eyes: <span class="hljs-built_in">number</span> 
}
</code></pre>
<h4 id="heading-type-alias-extends-an-interface">Type alias extends an interface</h4>
<pre><code class="lang-ts"><span class="hljs-keyword">interface</span> HumanWithName {
  name: <span class="hljs-built_in">string</span> 
}

<span class="hljs-keyword">type</span> Human = HumanWithName &amp; {
   legs: <span class="hljs-built_in">number</span> 
   eyes: <span class="hljs-built_in">number</span> 
}
</code></pre>
<h4 id="heading-interface-extends-an-interface">Interface extends an interface</h4>
<pre><code class="lang-ts"><span class="hljs-keyword">interface</span> HumanWithName {
  name: <span class="hljs-built_in">string</span> 
}

<span class="hljs-keyword">interface</span> Human <span class="hljs-keyword">extends</span> HumanWithName {
  legs: <span class="hljs-built_in">number</span> 
  eyes: <span class="hljs-built_in">number</span> 
}
</code></pre>
<h4 id="heading-interface-extends-a-type-alias">Interface extends a type alias</h4>
<pre><code class="lang-ts"><span class="hljs-keyword">type</span> HumanWithName = {
  name: <span class="hljs-built_in">string</span>
}

<span class="hljs-keyword">interface</span> Human <span class="hljs-keyword">extends</span> HumanWithName {
  legs: <span class="hljs-built_in">number</span> 
  eyes: <span class="hljs-built_in">number</span> 
}
</code></pre>
<p>As you can see, this is not particularly a reason to choose one over the other. However, the syntaxes differ.</p>
<h3 id="heading-minor-difference-classes-can-only-implement-statically-known-members">Minor difference: classes can only implement statically known members</h3>
<p>A class can implement both interfaces or type aliases. However, a class cannot implement or extend a union type.</p>
<p>Consider the following example:</p>
<h4 id="heading-class-implements-an-interface">Class implements an interface</h4>
<pre><code class="lang-ts"><span class="hljs-keyword">interface</span> Human {
  name: <span class="hljs-built_in">string</span>
  legs: <span class="hljs-built_in">number</span> 
  eyes: <span class="hljs-built_in">number</span> 
}

<span class="hljs-keyword">class</span> FourLeggedHuman <span class="hljs-keyword">implements</span> Human {
  name = <span class="hljs-string">'Krizuga'</span>
  legs = <span class="hljs-number">4</span>
  eyes = <span class="hljs-number">2</span>
}
</code></pre>
<h4 id="heading-class-implements-a-type-alias">Class implements a type alias</h4>
<pre><code class="lang-ts"><span class="hljs-keyword">type</span> Human = {
  name: <span class="hljs-built_in">string</span>
  legs: <span class="hljs-built_in">number</span> 
  eyes: <span class="hljs-built_in">number</span> 
}

<span class="hljs-keyword">class</span> FourLeggedHuman <span class="hljs-keyword">implements</span> Human {
  name = <span class="hljs-string">'Krizuga'</span>
  legs = <span class="hljs-number">4</span>
  eyes = <span class="hljs-number">2</span>
}
</code></pre>
<p>Both these work without any errors. However, the following fails:</p>
<h4 id="heading-class-implements-a-union-type">Class implements a union type</h4>
<pre><code class="lang-ts"><span class="hljs-keyword">type</span> Human = {
    name: <span class="hljs-built_in">string</span>
} | {
    legs: <span class="hljs-built_in">number</span>
    eyes: <span class="hljs-built_in">number</span>
}

<span class="hljs-keyword">class</span> FourLeggedHuman <span class="hljs-keyword">implements</span> Human {
    name = <span class="hljs-string">'Krizuga'</span>
    legs = <span class="hljs-number">4</span>
    eyes = <span class="hljs-number">2</span>
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/image-55.png" alt="Image" width="600" height="400" loading="lazy">
<em>A class can only implement an object type or intersection of object types with statically known members.</em></p>
<p>See the <a target="_blank" href="https://www.typescriptlang.org/play?#code/C4TwDgpgBAEgrgWwIYDsoF4oG8BQV9QpIIQBcUAzsAE4CWKA5jgL5QA+2eBANhAxeRSIARhGpd8EEBAGERYljhwBjbkgoUoAMQD2cagBk+DCABN4yNLQRheJFME0XUnAoWLRMAcgDSdAF5wDEheElC8-BhQACxhUjJRAEwsQA">TypeScript playground</a>.</p>
<h2 id="heading-summary-of-type-aliases-vs-interfaces">Summary of Type Aliases vs Interfaces</h2>
<p>Your mileage may differ, but wherever possible, I stick to type aliases for their flexibility and simpler syntax. That is, I pick type aliases except I specifically need features from an interface.</p>
<p>For the most part, you can also decide based on your personal preference, but stay consistent with your choice — at least in a single given project.</p>
<p>For completeness, I must add that in performance critical types, interface comparison checks can be faster than type aliases. I’m yet to find this to be an issue.</p>
<h1 id="heading-in-typescript-what-is-the-exclamation-mark-bang-operator">In TypeScript, What is the ! (Exclamation Mark / Bang) Operator?</h1>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/image-56.png" alt="Image" width="600" height="400" loading="lazy">
<em>What is the bang operator in TypeScript?</em></p>
<h2 id="heading-tldr-1">TL;DR</h2>
<p>This <code>!</code> is technically called the <strong>non-null assertion operator</strong>. If the TypeScript compiler complains about a value being <code>null</code> or <code>undefined</code>, you can use the <code>!</code> operator to assert that the said value is not <code>null</code> or <code>undefined</code>.</p>
<p>Personal take: avoid doing this wherever possible.</p>
<h2 id="heading-what-is-the-non-null-assertion-operator">What is the Non-Null Assertion Operator?</h2>
<p><code>null</code> and <code>undefined</code> are valid JavaScript values.</p>
<p>The statement above holds true for all TypeScript applications as well.</p>
<p>However, TypeScript goes one step further.</p>
<p><code>null</code> and <code>undefined</code> are equally valid types. For example, consider the following:</p>
<pre><code class="lang-ts"><span class="hljs-comment">// explicit null</span>
<span class="hljs-keyword">let</span> a: <span class="hljs-literal">null</span> 

a = <span class="hljs-literal">null</span>
<span class="hljs-comment">// the following assignments will yield errors</span>
a= <span class="hljs-literal">undefined</span> 
a = {}


<span class="hljs-comment">// explicit undefined</span>
<span class="hljs-keyword">let</span> b: <span class="hljs-literal">undefined</span> 
<span class="hljs-comment">// the following assignments will yield errors</span>
b = <span class="hljs-literal">null</span> 
b = {}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/image-57.png" alt="Image" width="600" height="400" loading="lazy">
<em>Error: values other than null and undefined not assignable</em></p>
<p>See the <a target="_blank" href="https://www.typescriptlang.org/play?#code/DYUwLgBAhgXBB2BXYwICg1QgXgc4aA9IRGABYgQBmA9ijQO4CW8A5tAM4dOvwC2IeGA4RmKCAE8mIYABMIIAE6KaijplyJ4skFRYh5mHBADeAXwxpQkAEZwtOvfAPpipCtTrBGLdlC48-ILCokziUjLySipqaDbGSOJxxuZoQA">TypeScript playground</a>.</p>
<p>In certain cases, the TypeScript compiler cannot tell whether a certain value is defined or not, that is not <code>null</code> or <code>undefined</code>.</p>
<p>For example, assume you had a value <code>Foo</code>.</p>
<p><code>Foo!</code> produces a value of the type of <code>Foo</code> with <code>null</code> and <code>undefined</code> excluded.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/image-58.png" alt="Image" width="600" height="400" loading="lazy">
<em>Foo! excludes null and undefined from the type of Foo</em></p>
<p>You essentially say to the TypeScript compiler, <em>I am sure <code>Foo</code> will NOT be <code>null</code> or <code>undefined</code></em>.</p>
<p>Let’s explore a naïve example.</p>
<p>In standard JavaScript, you may concatenate two strings with the <code>.concat</code> method:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">const</span> str1 = <span class="hljs-string">"Hello"</span> 
<span class="hljs-keyword">const</span> str2 = <span class="hljs-string">"World"</span>

<span class="hljs-keyword">const</span> greeting = str1.concat(<span class="hljs-string">' '</span>, str2)
<span class="hljs-comment">// Hello World</span>
</code></pre>
<p>Write a simple duplicate string function that calls <code>.concat</code> with itself as an argument:</p>
<pre><code class="lang-ts"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">duplicate</span>(<span class="hljs-params">text: <span class="hljs-built_in">string</span> | <span class="hljs-literal">null</span></span>) </span>{
  <span class="hljs-keyword">return</span> text.concat(text);
}
</code></pre>
<p>Note that the argument <code>text</code> is typed as <code>string | null</code>.</p>
<p>In strict mode, TypeScript will complain here, as calling <code>concat</code> with <code>null</code> can lead to unexpected results.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/image-59.png" alt="Image" width="600" height="400" loading="lazy">
<em>The result of calling concat with null</em></p>
<p>The TypeScript error will read: <code>Object is possibly 'null'.(2531)</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/image-60.png" alt="Image" width="600" height="400" loading="lazy">
<em>Typescript error: Object is possibly null</em></p>
<p>On the flip side, a rather lazy way to silence the compiler error is to use the non-null assertion operator:</p>
<pre><code class="lang-ts"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">duplicate</span>(<span class="hljs-params">text: <span class="hljs-built_in">string</span> | <span class="hljs-literal">null</span></span>) </span>{
  <span class="hljs-keyword">return</span> text!.concat(text!);
}
</code></pre>
<p>Note the exclamation mark after the <code>text</code> variable – <code>text!</code>.</p>
<p>The <code>text</code> type represents <code>string | null</code>.</p>
<p><code>text!</code> represents just <code>string</code>, that is with <code>null</code> or <code>undefined</code> removed from the variable type.</p>
<p>The result? You’ve silenced the TypeScript error.</p>
<p>However, this is a silly fix.</p>
<p><code>duplicate</code> can indeed be called with <code>null</code>, which may lead to unexpected results.</p>
<p>Note that the following example also holds true if <code>text</code> is an optional property:</p>
<pre><code class="lang-ts"><span class="hljs-comment">// text could be "undefined"</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">duplicate</span>(<span class="hljs-params">text?: <span class="hljs-built_in">string</span></span>) </span>{
  <span class="hljs-keyword">return</span> text!.concat(text!);
}
</code></pre>
<h2 id="heading-pitfalls-of-the-operator-and-what-to-do-instead">Pitfalls of the <code>!</code> Operator (and What to Do Instead)</h2>
<p>When working with TypeScript as a new user, you may feel like you’re fighting a losing battle.</p>
<p>The errors don’t make sense to you.</p>
<p>Your goal is to remove the error and move on with your life as swiftly as you can.</p>
<p>However, you should be careful with using the non-null assertion operator.</p>
<p>Silencing a TypeScript error doesn’t mean there may not still be an underlying issue—if unaddressed.</p>
<p>As you saw in the earlier example, you lose every relevant TypeScript safety against wrong usages where <code>null</code> and <code>undefined</code> could be unwanted.</p>
<p>So, what should you do?</p>
<p>If you write React, consider an example you’re likely familiar with:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">const</span> MyComponent = <span class="hljs-function">() =&gt;</span> {
   <span class="hljs-keyword">const</span> ref = React.createRef&lt;HTMLInputElement&gt;();

   <span class="hljs-comment">//compilation error: ref.current is possibly null</span>
   <span class="hljs-keyword">const</span> goToInput = <span class="hljs-function">() =&gt;</span> ref.current.scrollIntoView(); 

    <span class="hljs-keyword">return</span> (
       &lt;div&gt;
           &lt;input ref={ref}/&gt;
           &lt;button onClick={goToInput}&gt;Go to Input&lt;/button&gt;
       &lt;/div&gt;
   );
};
</code></pre>
<p>In the example above (for those who do not write React), in the <code>React</code> mental model, <code>ref.current</code> will certainly be available at the time the button is clicked by the user.</p>
<p>The <code>ref</code> object is set soon after the UI elements are rendered.</p>
<p>TypeScript does not know this, and you may be forced to use the non-null assertion operator here.</p>
<p>Essentially, say to the TypeScript compiler, I know what I’m doing, you don’t.</p>
<pre><code class="lang-ts"><span class="hljs-keyword">const</span> goToInput = <span class="hljs-function">() =&gt;</span> ref.current!.scrollIntoView();
</code></pre>
<p>Note the exclamation mark <code>!</code>.</p>
<p>This “fixes” the error.</p>
<p>However, if in the future, someone removes the <code>ref</code> from the input, and there were no automated tests to catch this, you now have a bug.</p>
<pre><code class="lang-ts"><span class="hljs-comment">// before</span>
&lt;input ref={ref}/&gt;

<span class="hljs-comment">// after</span>
&lt;input /&gt;
</code></pre>
<p>TypeScript will be unable to spot the error in the following line:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">const</span> goToInput = <span class="hljs-function">() =&gt;</span> ref.current!.scrollIntoView();
</code></pre>
<p>By using the non-null assertion operator, the TypeScript compiler will act as if <code>null</code> and <code>undefined</code> are never possible for the value in question. In this case, <code>ref.current</code>.</p>
<h3 id="heading-solution-1-find-an-alternative-fix">Solution 1: Find an Alternative Fix</h3>
<p>The first line of action you should employ is to find an alternative fix.</p>
<p>For example, often you can explicitly check for <code>null</code> and <code>undefined</code> values like this:</p>
<pre><code class="lang-ts"><span class="hljs-comment">// before </span>
<span class="hljs-keyword">const</span> goToInput = <span class="hljs-function">() =&gt;</span> ref.current!.scrollIntoView();

<span class="hljs-comment">// now </span>
<span class="hljs-keyword">const</span> goToInput = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">if</span> (ref.current) {
   <span class="hljs-comment">//Typescript will understand that ref.current is certianly </span>
   <span class="hljs-comment">//avaialble in this branch</span>
     ref.current.scrollIntoView()
  }
};

<span class="hljs-comment">// alternatively (use the logical AND operator)</span>
<span class="hljs-keyword">const</span> goToInput = <span class="hljs-function">() =&gt;</span> ref.current &amp;&amp; ref.current.scrollIntoView();
</code></pre>
<p>Numerous engineers will argue over the fact that this is more verbose.</p>
<p>That’s correct.</p>
<p>But you should choose verbose over possibly breaking code being pushed to production.</p>
<p>This is a personal preference. Your mileage may differ.</p>
<h3 id="heading-solution-2-explicitly-throw-an-error">Solution 2: Explicitly Throw an Error</h3>
<p>In cases where an alternative fix doesn’t cut it and the non-null assertion operator seems like the only solution, I typically advise you throw an error before doing this.</p>
<p>Here’s an example (in pseudocode):</p>
<pre><code class="lang-ts"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">doSomething</span> (<span class="hljs-params">value</span>) </span>{
   <span class="hljs-comment">// for some reason TS thinks the value could be  </span>
   <span class="hljs-comment">// null or undefined but you disagree</span>

  <span class="hljs-keyword">if</span>(!value) {
    <span class="hljs-comment">// explicilty assert this is the case </span>
    <span class="hljs-comment">// throw an error or log this somewhere you can trace</span>
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'uexpected error: value not present'</span>)
  } 

  <span class="hljs-comment">// go ahead and use the non-null assertion operator</span>
  <span class="hljs-built_in">console</span>.log(value)
}
</code></pre>
<p>A practical case where I’ve found myself sometimes doing this is while using <code>Formik</code>.</p>
<p>Except things have changed, and I do think <code>Formik</code> is poorly typed in numerous instances.</p>
<p>The example may go similarly if you've done your Formik validation and are sure that your values exist.</p>
<p>Here’s some pseudocode:</p>
<pre><code class="lang-ts">&lt;Formik 
  validationSchema={...} 
  onSubmit={<span class="hljs-function">(<span class="hljs-params">values</span>) =&gt;</span> {
   <span class="hljs-comment">// you are sure values.name should exist because you had </span>
   <span class="hljs-comment">// validated in validationSchema but TypeScript doesn't know this</span>

   <span class="hljs-keyword">if</span>(!values.name) {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Invalid form, name is required'</span>)        
   } 
   <span class="hljs-built_in">console</span>.log(values.name!)
}}&gt;


&lt;/Formik&gt;
</code></pre>
<p>In the pseudocode above, <code>values</code> could be typed as:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">type</span> Values = {
  name?: <span class="hljs-built_in">string</span>
}
</code></pre>
<p>But before you hit <code>onSubmit</code>, you’ve added some validation to show a UI form error for the user to input a <code>name</code> before moving on to the form submission.</p>
<p>There are other ways to get around this. But if you’re sure a value exists but can’t quite communicate that to the TypeScript compiler, use the non-null assertion operator. But also add an assertion of your own by throwing an error you can trace.</p>
<h2 id="heading-how-about-an-implicit-assertion">How About an Implicit Assertion?</h2>
<p>Even though the name of the operator reads non-null assertion operator, no “assertion” is actually being made.</p>
<p>You’re mostly asserting (as the developer) that the value exists.</p>
<p>The TypeScript compiler does NOT assert that this value exists.</p>
<p>So, if you must, you may go ahead and add your assertion (for example as discussed in the earlier section).</p>
<p>Also, note that no more JavaScript code is emitted by using the non-null assertion operator.</p>
<p>As stated earlier, there’s no assertion done here by TypeScript.</p>
<p>Consequently, TypeScript will not emit some code that checks if this value exists or not.</p>
<p>The JavaScript code emitted will act as if this value always existed.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/image-62.png" alt="Image" width="600" height="400" loading="lazy">
<em>Emitted javascript code same as Javascript</em></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>TypeScript 2.0 saw the release of the <strong>non-null assertion operator</strong>. Yes, it’s been around for some time (<a target="_blank" href="https://github.com/microsoft/TypeScript/releases/tag/v2.0.3">released in 2016</a>). At the time of writing, the latest version of TypeScript is <code>v4.7</code>.</p>
<p>If the TypeScript compiler complains about a value being <code>null</code> or <code>undefined</code>, you can use the <code>!</code> operator to assert that the said value is not null or undefined.</p>
<p>Only do this if you’re certain that is the case.</p>
<p>Even better, go ahead and add an assertion of your own, or try to find an alternative solution.</p>
<p>Some may argue that if you need to use the non-null assertion operator every time, it’s a sign you’re poorly representing the state of your application state via TypeScript.</p>
<p>I agree with this school of thought.</p>
<h1 id="heading-what-is-a-dts-file-in-typescript">What is a “.d.ts” File in TypeScript?</h1>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/image-63.png" alt="Image" width="600" height="400" loading="lazy">
<em>What is a d.ts file?</em></p>
<h2 id="heading-tldr-2">TL;DR</h2>
<p><code>.d.ts</code> files are called type declaration files. They exist for one purpose only: to describe the shape of an existing module and they only contain type information used for type checking.</p>
<h2 id="heading-introduction-to-dts-files-in-typescript">Introduction to <code>.d.ts</code> Files in TypeScript</h2>
<p>Upon learning the basics of TypeScript, you unlock superpowers.</p>
<p>At least that’s how I felt.</p>
<p>You automagically get warnings on potential errors and you get auto-completion out of the box in your code editor.</p>
<p>While seemingly magical, nothing with computers really is.</p>
<p>So, what’s the trick here, TypeScript?</p>
<p>In clearer language, how does TypeScript know so much? How does it decide what API is correct or not? What methods are available on a certain object or class, and which aren’t?</p>
<p>The answer is less magical.</p>
<p>TypeScript relies on types.</p>
<p>Occasionally, you do not write these types, but they exist.</p>
<p>They exist in files called declaration files.</p>
<p>These are files with a <code>.d.ts</code> ending.</p>
<h2 id="heading-a-simple-example-of-dts-files">A Simple Example of <code>.d.ts</code> Files</h2>
<p>Consider the following TypeScript code:</p>
<pre><code class="lang-ts"><span class="hljs-comment">// valid </span>
<span class="hljs-keyword">const</span> amount = <span class="hljs-built_in">Math</span>.ceil(<span class="hljs-number">14.99</span>)

<span class="hljs-comment">// error: Property 'ciil' does not exist on type 'Math'.(2339)</span>
<span class="hljs-keyword">const</span> otherAmount = <span class="hljs-built_in">Math</span>.ciil(<span class="hljs-number">14.99</span>)
</code></pre>
<p>See the <a target="_blank" href="https://www.TypeScriptlang.org/play?#code/MYewdgzgLgBAhgWxAVzLAvDAsnKALAOmAFMBLAGwAoBGAFgIE4GBKAKFdElhH2ICcAgklQZsuQsFIUa9Jm1ZA">TypeScript playground</a>.</p>
<p>The first line of code is perfectly valid, but the second, not quite.</p>
<p>And TypeScript is quick to spot the error: <code>Property 'ciil' does not exist on type 'Math'.(2339)</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/image-64.png" alt="Image" width="600" height="400" loading="lazy">
<em>The Typescript error spotting the wrong property access "ciil"</em></p>
<p>How did TypeScript know <code>ciil</code> does not exist on the <code>Math</code> object?</p>
<p>The <code>Math</code> object isn’t a part of our implementation. It’s a standard built-in object.</p>
<p>So, how did TypeScript figure that out?</p>
<p>The answer is there are <strong>declaration files</strong> that describe these built-in objects.</p>
<p>Think of a declaration file as containing all type information relating to a certain module. It contains no actual implementation, just type information.</p>
<p>These files have a <code>.d.ts</code> ending.</p>
<p>Your implementation files will either have <code>.ts</code> or <code>.js</code> endings to represent TypeScript or JavaScript files.</p>
<p>These declaration files have no implementations. They only contain type information and have a <code>.d.ts</code> file ending.</p>
<h2 id="heading-built-in-type-definitions">Built-in Type Definitions</h2>
<p>A great way to understand this in practice is to set up a brand new TypeScript project and explore the type definition files for top-level objects like <code>Math</code>.</p>
<p>Let’s do this.</p>
<p>Create a new directory, and name it whatever’s appropriate.</p>
<p>I’ll call mine <code>dts</code>.</p>
<p>Change directories to this newly created folder:</p>
<pre><code class="lang-ts">cd dts
</code></pre>
<p>Now initialise a new project:</p>
<pre><code class="lang-ts">npm init --yes
</code></pre>
<p>Install TypeScript:</p>
<pre><code class="lang-ts">npm install TypeScript --save-dev
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/image-65.png" alt="Image" width="600" height="400" loading="lazy">
<em>Installing TypeScript</em></p>
<p>This directory should contain 2 files and one subdirectory:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/image-66.png" alt="Image" width="600" height="400" loading="lazy">
<em>The files after installation</em></p>
<p>Open the folder in your favourite code editor.</p>
<p>If you investigate the <code>TypeScript</code> directory within <code>node_modules</code>, you’ll find a bunch of type declaration files out of the box.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/image-67.png" alt="Image" width="600" height="400" loading="lazy">
<em>Type declaration files in the TypeScript directory</em></p>
<p>These are present courtesy of installing TypeScript.</p>
<p>By default, TypeScript will include type definition for all DOM APIs, for example think <code>window</code> and <code>document</code>.</p>
<p>As you inspect these type declaration files, you’ll notice that the naming convention is straightforward.</p>
<p>It follows the pattern: <code>lib.[something].d.ts</code>.</p>
<p>Open up the <code>lib.dom.d.ts</code> declaration file to view all declarations related to the browser DOM API.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/image-68.png" alt="Image" width="600" height="400" loading="lazy">
<em>The dom declaration file</em></p>
<p>As you can see, this is quite a gigantic file.</p>
<p>But so are all the APIs available in the DOM.</p>
<p>Awesome!</p>
<p>Now, if you take a look at the <code>lib.es5.d.ts</code> file, you’ll see the declaration for the <code>Math</code> object, containing the <code>ceil</code> property.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/image-69.png" alt="Image" width="600" height="400" loading="lazy">
<em>The Math object in the declaration file</em></p>
<p>Next time you think, wow, TypeScript is wonderful. Remember, a big part of that awesomeness is due to the lesser-known heroes: type declaration files.</p>
<p>It’s not magic. Just type declaration files.</p>
<h2 id="heading-external-type-definitions-in-typescript">External Type Definitions in TypeScript</h2>
<p>What about APIs that aren’t built-in?</p>
<p>There’s a host of <code>npm</code> packages out there to do just about anything you want.</p>
<p>Is there a way for TypeScript to also understand the relevant type relationships for the said module?</p>
<p>Well, the answer is a resounding yes.</p>
<p>There are typically two ways a library author may do this.</p>
<h3 id="heading-bundled-types">Bundled Types</h3>
<p>In this case, the author of the library has already bundled the type declaration files as part of the package distribution.</p>
<p>You typically don’t need to do anything.</p>
<p>You just go ahead and install the library in your project, you import the required module from the library and see if TypeScript should automatically resolve the types for you.</p>
<p>Remember, this is not magic.</p>
<p>The library author has bundled the type declaration file in the package distribution.</p>
<h3 id="heading-definitelytyped-types">DefinitelyTyped (@types)</h3>
<p>Imagine a central public repository that hosts declaration files for thousands of libraries?</p>
<p>Well, bring that image home.</p>
<p>This repository already exists.</p>
<p>The <a target="_blank" href="https://github.com/DefinitelyTyped/DefinitelyTyped/">DefinitelyTyped repository</a> is a centralised repository that stores the declaration files for thousands of libraries.</p>
<p>In all honestly, the vast majority of commonly used libraries have declaration files available on <strong>DefinitelyTyped</strong>.</p>
<p>These type definition files are automatically published to <code>npm</code> under the <code>@types</code> scope.</p>
<p>For example, if you wanted to install the types for the <code>react</code> npm package, you’d do this:</p>
<pre><code class="lang-ts">npm install --save-dev <span class="hljs-meta">@types</span>/react
</code></pre>
<p>If you find yourself using a module whose types TypeScript does not automatically resolve, attempt installing the types directly from DefinitelyTyped.</p>
<p>See if the types exist there. For example:</p>
<pre><code class="lang-ts">npm install --save-dev <span class="hljs-meta">@types</span>/your-library
</code></pre>
<p>Definition files that you add in this manner will be saved to <code>node_modules/@types</code>.</p>
<p>TypeScript will automatically find these. So, there’s no additional step for you to take.</p>
<h2 id="heading-how-to-write-your-own-declaration-files">How to Write Your Own Declaration Files</h2>
<p>In the uncommon event that a library didn’t bundle its types and does not have a type definition file on DefinitelyTyped, you can write your own declaration files.</p>
<p>Writing declaration files in-depth is beyond the scope of this article, but a use case you’ll likely come across is silencing errors about a particular module without a declaration file.</p>
<p>Declaration files all have a <code>.d.ts</code> ending.</p>
<p>So to create yours, create a file with a <code>.d.ts</code> ending.</p>
<p>For example, assume I have installed the library <code>untyped-module</code> in my project.</p>
<p><code>untyped-module</code> has no referenced type definition files, so TypeScript complains about this in my project.</p>
<p>To silence this warning, I may create a new <code>untyped-module.d.ts</code> file in my project with the following content:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">declare</span> <span class="hljs-keyword">module</span> "some-untyped-<span class="hljs-keyword">module</span>";
</code></pre>
<p>This will declare the module as type <code>any</code>.</p>
<p>We won’t get any TypeScript support for that module, but you’d have silenced the TypeScript warning.</p>
<p>Ideal next steps would include opening an issue in the module’s public repository to include a TypeScript declaration file, or writing out a decent one yourself.</p>
<h2 id="heading-conclusion-1">Conclusion</h2>
<p>Next time you think, wow, TypeScript is remarkable. Remember, a big part of that awesomeness is due to the lesser-known heroes: type declaration files.</p>
<p>Now you understand how they work!</p>
<h1 id="heading-how-do-you-explicitly-set-a-new-property-on-window-in-typescript">How Do You Explicitly Set a New Property on <code>window</code> in Typescript?</h1>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/image-70.png" alt="Image" width="600" height="400" loading="lazy">
<em>Set a new property on the window object?</em></p>
<h2 id="heading-tldr-3">TL;DR</h2>
<p>Extend the existing interface declaration for the <code>Window</code> object.</p>
<h2 id="heading-introduction-to-window-in-typescript">Introduction to <code>window</code> in TypeScript</h2>
<p>Knowledge builds upon knowledge.</p>
<p>Whoever said that was right.</p>
<p>In this section, we will build upon the knowledge from the last two sections:</p>
<ul>
<li><a target="_blank" href="https://blog.ohansemmanuel.com/interfaces-vs-types-in-typescript/">Interfaces vs Types in TypeScript</a></li>
<li><a target="_blank" href="https://blog.ohansemmanuel.com/what-is-a-dts-file-in-typescript/">What is a d.t.s file in TypeScript</a>?</li>
</ul>
<p>Ready?</p>
<p>First, I must say, in my early days with TypeScript, this was a question I googled over and over again.</p>
<p>I never got it. And I didn’t bother, I just googled.</p>
<p>That’s never the right mentality to gaining mastery over a subject.</p>
<p>Let’s discuss the solutions to this.</p>
<h2 id="heading-understanding-the-problem">Understanding the Problem</h2>
<p>The problem here is actually straightforward to reason about.</p>
<p>Consider the following TypeScript code:</p>
<pre><code class="lang-ts"><span class="hljs-built_in">window</span>.__MY_APPLICATION_NAME__ = <span class="hljs-string">"freecodecamp"</span>

<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">window</span>.__MY_APPLICATION_NAME__)
</code></pre>
<p>TypeScript is quick to let you know <code>__MY_APPLICATION_NAME__</code> does not exist on type ‘Window &amp; typeof globalThis’.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/image-71.png" alt="Image" width="600" height="400" loading="lazy">
<em>The property does not exist on Window error</em></p>
<p>See the <a target="_blank" href="https://www.freecodecamp.org/news/p/a31cc449-928c-4453-a83d-ce30ef79f986/%20https://www.typescriptlang.org/play?#code/O4SwdgJg9sB0D68CyBNeBBACpgMgSQGF0AVPAeQDl4L0kBRRAAgF5GAiAMwCcBTHgYygQBAQwC2ABzYAoaYLABnKABsesZVADmAClCQYCZGiy5CJclRr1EASln2gA">TypeScript playground</a>.</p>
<p>Okay, TypeScript.</p>
<p>We get it.</p>
<p>On closer inspection, remember from the last section on <a target="_blank" href="https://blog.ohansemmanuel.com/what-is-a-dts-file-in-typescript/">declaration files</a> that there’s a declaration file for all existing browser APIs. This includes built-in objects such as <code>window</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/image-72.png" alt="Image" width="600" height="400" loading="lazy">
<em>The default Window interface declaration</em></p>
<p>If you look in the <code>lib.dom.d.ts</code> declaration file, you’ll find the <code>Window</code> interface described.</p>
<p>In layperson’s terms, the error here says the <code>Window</code> interface describes how I understand the <code>window</code> object and its usage. That interface does not specify a certain <code>__MY_APPLICATION_NAME__</code> property.</p>
<h2 id="heading-how-to-fix-the-error">How to Fix the Error</h2>
<p>In the types vs interface section, I explained how to extend an interface.</p>
<p>Let’s apply that knowledge here.</p>
<p>We can extend the <code>Window</code> interface declaration to become aware of the <code>__MY_APPLICATION_NAME__</code> property.</p>
<p>Here’s how:</p>
<pre><code class="lang-ts"><span class="hljs-comment">// before</span>
<span class="hljs-built_in">window</span>.__MY_APPLICATION_NAME__ = <span class="hljs-string">"freecodecamp"</span>

<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">window</span>.__MY_APPLICATION_NAME__)

<span class="hljs-comment">// now </span>
<span class="hljs-keyword">interface</span> Window {
  __MY_APPLICATION_NAME__: <span class="hljs-built_in">string</span>
}

<span class="hljs-built_in">window</span>.__MY_APPLICATION_NAME__ = <span class="hljs-string">"freecodecamp"</span>

<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">window</span>.__MY_APPLICATION_NAME__)
</code></pre>
<p>Errors banished!</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/image-74.png" alt="Image" width="600" height="400" loading="lazy">
<em>The resolved solution</em></p>
<p>See the <a target="_blank" href="https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgOqgCYHsDuyDeAUMsgPqkCyAmqQIIAK9AMgJIDCtAKiwPIBypPrQoBRcgC5kAZzBRQAc0IBfQoRyZcAOnLU6jVh279BwsaWQBeZACIYUCBARYMjuAFsADtdVOQUrAA2EJoBWPIAFOog2DjalDQMzOxcvAJCouQAlEA">TypeScript playground</a>.</p>
<p>Remember that a key difference between types and interfaces is that interfaces can be extended by declaring it multiple times.</p>
<p>What we’ve done here is declared the <code>Window</code> interface one more time, hence extending the interface declaration.</p>
<h3 id="heading-a-real-world-solution">A Real-World Solution</h3>
<p>I’ve solved this problem within the TypeScript playground to show you the solution in its simplest form, that is the crux.</p>
<p>In the real world, though, you wouldn’t extend the interface within your code.</p>
<p>So, what should you do instead?</p>
<p>Give it a guess, perhaps?</p>
<p>Yes, you were close … or perhaps right:</p>
<p>Create a type definition file!</p>
<p>For example, create a <code>window.d.ts</code> file with the following content:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">interface</span> Window {
  __MY_APPLICATION_NAME__: <span class="hljs-built_in">string</span>
}
</code></pre>
<p>And there you go.</p>
<p>You’ve successfully extended the <code>Window</code> interface and solved the problem.</p>
<p>If you went ahead to assign the wrong value type to the <code>__MY_APPLICATION_NAME__</code> property, you now have strong type checking enabled.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/image-75.png" alt="Image" width="600" height="400" loading="lazy">
<em>A wrong assignment to the newly defined property caught</em></p>
<p>See the <a target="_blank" href="https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgOqgCYHsDuyDeAUMsgPqkCyAmqQIIAK9AMgJIDCtAKiwPIBypPrQoBRcgC5kAZzBRQAc0IBfQoRyZcAOnLU6jVh279BwsaWQBeAsWQg4AWwiSARDCgQICLBk8OADs7Kql4gUlgANhCa4VjyABTqINg42pQ0DMzsXLwCQqLkAJSqxUA">TypeScript playground</a>.</p>
<p>_And _Voilà.__</p>
<h2 id="heading-conclusion-2">Conclusion</h2>
<p>In <a target="_blank" href="https://stackoverflow.com/questions/12709074/how-do-you-explicitly-set-a-new-property-on-window-in-typescript">older stack overflow posts</a>, you’ll find more complicated answers based on older TypeScript versions.</p>
<p>The solution is easier to reason about in modern TypeScript.</p>
<p>Now you know. 😉</p>
<h1 id="heading-are-strongly-typed-functions-as-parameters-possible-in-typescript">Are Strongly Typed Functions as Parameters Possible in TypeScript?</h1>
<h2 id="heading-tldr-4">TL;DR</h2>
<p>This question does not need to be overly explained. The short answer is yes.</p>
<p>Functions can be strongly typed — even as parameters to other functions.</p>
<h2 id="heading-introduction">Introduction</h2>
<p>I must say, unlike other sections of this article, I never really found myself searching for this in my early TypeScript days.</p>
<p>However, that’s not what’s most important.</p>
<p>It is a well-searched question, so let’s answer it!</p>
<h2 id="heading-how-to-use-strongly-typed-function-parameters-in-typescript">How to Use Strongly Typed Function Parameters in TypeScript</h2>
<p>The accepted answer on this <a target="_blank" href="https://stackoverflow.com/questions/14638990/are-strongly-typed-functions-as-parameters-possible-in-typescript">stack overflow post</a> is correct — to a degree.</p>
<p>Assuming you had a function: <code>speak</code>:</p>
<pre><code class="lang-ts"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">speak</span>(<span class="hljs-params">callback</span>) </span>{
  <span class="hljs-keyword">const</span> sentence = <span class="hljs-string">"Hello world"</span>
  alert(callback(sentence))
}
</code></pre>
<p>It receives a <code>callback</code> that’s internally invoked with a <code>string</code>.</p>
<p>To type this, go ahead and represent the <code>callback</code> with a function type alias:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">type</span> Callback = <span class="hljs-function">(<span class="hljs-params">value: <span class="hljs-built_in">string</span></span>) =&gt;</span> <span class="hljs-built_in">void</span>
</code></pre>
<p>And type the <code>speak</code> function as follows:</p>
<pre><code class="lang-ts"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">speak</span>(<span class="hljs-params">callback: Callback</span>) </span>{
  <span class="hljs-keyword">const</span> sentence = <span class="hljs-string">"Hello world"</span>
  alert(callback(sentence))
}
</code></pre>
<p>Alternatively, you could also keep the type inline:</p>
<pre><code class="lang-ts"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">speak</span>(<span class="hljs-params">callback: (value: <span class="hljs-built_in">string</span>) =&gt; <span class="hljs-built_in">void</span></span>) </span>{
  <span class="hljs-keyword">const</span> sentence = <span class="hljs-string">"Hello world"</span>

  alert(callback(sentence))
}
</code></pre>
<p>See the <a target="_blank" href="https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABAZwA4FMCGBrAFBTAG0ICNMJsAuRXANyJHWuSgCcYwBzASkQF4AfIlpwYAE14BvAFCJEEBCxTowUFRHT9EAIgAS6YnEQB3OK0Jjt02YiLpWUfEVLk8yFWsjpu3aQF9rQOkgA">TypeScript playground</a>.</p>
<p>And there it is!</p>
<p>You’ve used a strongly typed function as a parameter.</p>
<h2 id="heading-how-to-handle-functions-with-no-return-value">How to Handle Functions with No Return Value</h2>
<p>The accepted answer in the referenced stack overflow post for example says <em>the callback parameter's type must be</em> a <em>"function that accepts a number and returns type any</em>.<em>"</em></p>
<p>That’s partly true, but the return type does NOT have to be <code>any</code>.</p>
<p>In fact, do NOT use <code>any</code>.</p>
<p>If your function returns a value, go ahead and type it appropriately:</p>
<pre><code class="lang-ts"><span class="hljs-comment">// Callback returns an object</span>
<span class="hljs-keyword">type</span> Callback = <span class="hljs-function">(<span class="hljs-params">value: <span class="hljs-built_in">string</span></span>) =&gt;</span> { result: <span class="hljs-built_in">string</span> }
</code></pre>
<p>If your callback returns nothing, use <code>void</code> not <code>any</code>:</p>
<pre><code class="lang-ts"><span class="hljs-comment">// Callback returns nothing</span>
<span class="hljs-keyword">type</span> Callback = <span class="hljs-function">(<span class="hljs-params">value: <span class="hljs-built_in">string</span></span>) =&gt;</span> <span class="hljs-built_in">void</span>
</code></pre>
<p>Note that the signature of your function type should be:</p>
<pre><code class="lang-ts">(arg1: Arg1type, arg2: Arg2type) =&gt; ReturnType
</code></pre>
<p>Where <code>Arg1type</code> represents the type of the argument <code>arg1</code>, <code>Arg2type</code> the type of the <code>arg2</code> argument, and <code>ReturnType</code> the return type of your function.</p>
<h2 id="heading-conclusion-3">Conclusion</h2>
<p>Functions are the primary means of passing data around in JavaScript.</p>
<p>TypeScript not only allows you to specify the input and output of functions, but you can also type functions as arguments to other functions.</p>
<p>Go ahead and use them with confidence.</p>
<h1 id="heading-how-to-fix-could-not-find-declaration-file-for-module">How to Fix Could Not Find Declaration File for Module …?</h1>
<p>This is a common source of frustration for TypeScript beginners.</p>
<p>However, do you know how to fix this?</p>
<p>Yes, you do!</p>
<p>We saw the solution to this in the <em>what is <code>d.ts</code></em> section<em>.</em></p>
<h2 id="heading-tldr-5">TL;DR</h2>
<p>Create a declaration file, for example <code>untyped-module.d.ts</code>, with the following content: <code>declare module "some-untyped-module";</code>. Note that this will explicitly type the module as <code>any</code>.</p>
<h2 id="heading-the-solution-explained">The Solution Explained</h2>
<p>You can give the writing your declaration files section a fresh read if you don’t remember how to fix this.</p>
<p>Essentially, you have this error because the library in question didn’t bundle its types and does not have a type definition file on <a target="_blank" href="https://github.com/DefinitelyTyped/DefinitelyTyped/">DefinitelyTyped</a>.</p>
<p>This leaves you with one solution: write your own declaration file.</p>
<p>For example, if you have installed the library <code>untyped-module</code> in your project, <code>untyped-module</code> has no referenced type definition files, so TypeScript complains.</p>
<p>To silence this warning, create a new <code>untyped-module.d.ts</code> file in your project with the following content:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">declare</span> <span class="hljs-keyword">module</span> "some-untyped-<span class="hljs-keyword">module</span>";
</code></pre>
<p>This will declare the module as type <code>any</code>.</p>
<p>You won’t get any TypeScript support for that module, but you’ll have silenced the TypeScript warning.</p>
<p>The ideal next steps would include opening an issue in the module’s public repository to include a TypeScript declaration file or writing out a decent one yourself (beyond the scope of this article).</p>
<h1 id="heading-how-do-i-dynamically-assign-properties-to-an-object-in-typescript">How Do I Dynamically Assign Properties to an Object in Typescript?</h1>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/image-76.png" alt="Image" width="600" height="400" loading="lazy">
<em>Dynamically assigning properties to objects in Typescript</em></p>
<h2 id="heading-tldr-6">TL;DR</h2>
<p>If you cannot define the variable type at declaration time, use the <code>Record</code> utility type or an object index signature.</p>
<h2 id="heading-introduction-1">Introduction</h2>
<p>Consider the following example:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">const</span> organization = {}

organization.name = <span class="hljs-string">"Freecodecamp"</span>
</code></pre>
<p>This seemingly harmless piece of code throws a TypeScript error on dynamically assigning <code>name</code> to the <code>organization</code> object.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/image-80.png" alt="Image" width="600" height="400" loading="lazy">
<em>Typescript error when adding a new property dynamically</em></p>
<p>See the <a target="_blank" href="https://www.typescriptlang.org/play?#code/MYewdgzgLgBCBOBzAhmAlgL2VN4YF4YBvAXwCgyEV0sdwA6MZAWwFMCYAiAMXlddAATASwAOnCjCnSZsufIWKlylarXqZFIA">Typescript playground</a></p>
<p>The source of confusion, and perhaps rightly justified if you’re a TypeScript beginner, is how is something seemingly so simple a problem in TypeScript?</p>
<h2 id="heading-understanding-the-problem-1">Understanding the Problem</h2>
<p>Generally speaking, TypeScript determines the type of a variable when it is declared, and this determined type doesn’t change – that is it stays the same all through your application.</p>
<p>There are exceptions to this rule when considering type narrowing or working with the any type, but this is a general rule to remember otherwise.</p>
<p>In the earlier example, the <code>organization</code> object is declared as follows:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">const</span> organization = {}
</code></pre>
<p>There is no explicit type assigned to the <code>organization</code> variable, so TypeScript infers the type of <code>organization</code> based on the declaration to be <code>{}</code>, that is the literal empty object.</p>
<p>For example, if you add a type alias, you can explore the type of <code>organization</code>:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">type</span> Org = <span class="hljs-keyword">typeof</span> organization
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/image-81.png" alt="Image" width="600" height="400" loading="lazy">
<em>Exploring the literal object type</em></p>
<p>See the <a target="_blank" href="https://www.typescriptlang.org/play?#code/MYewdgzgLgBCBOBzAhmAlgL2VN4YF4YBvAXwCgyoBPABwFMYB5JAma+kAMziVU21xgKCFOiw5wAOjDIAtg0IAiAGLw6dUABMNcmoooxDR4ydNnzFy1es3bd4xSA">TypeScript playground</a>.</p>
<p>When you then try to reference the <code>name</code> prop on this empty object literal:</p>
<pre><code class="lang-ts">organization.name = ...
</code></pre>
<p>TypeScript yells.</p>
<blockquote>
<p>Property 'name' does not exist on type ‘ <code>{}</code>‘.</p>
</blockquote>
<p>When you understand the issue, the error does seem appropriate.</p>
<p>Let’s fix this.</p>
<h2 id="heading-how-to-resolve-the-error">How to Resolve the Error</h2>
<p>There are numerous ways you can resolve the TypeScript error here. Let’s consider these:</p>
<h3 id="heading-1-explicitly-type-the-object-at-declaration-time">1. Explicitly type the object at declaration time</h3>
<p>This is the easiest solution to reason about.</p>
<p>At the time you declare the object, go ahead and type it. Furthermore, assign it all the relevant values.</p>
<pre><code class="lang-ts"><span class="hljs-keyword">type</span> Org = {
    name: <span class="hljs-built_in">string</span>
}

<span class="hljs-keyword">const</span> organization: Org = {
    name: <span class="hljs-string">"Freecodecamp"</span>
}
</code></pre>
<p>See the <a target="_blank" href="https://www.typescriptlang.org/play?#code/C4TwDgpgBA8gTgcygXigbwFBW1AdgQwFsIAuKAZ2DgEtcEMBfDDAYwHtdKo3F9dqAXvmDUOZeElSYceIqSgAiAGJwIEdgBN1RMAsbMDQA">TypeScript playground</a>.</p>
<p>This removes every surprise.</p>
<p>You’re clearly stating what this object type is and rightly declaring all relevant properties when you create the object.</p>
<p>However, this is not always feasible if the object properties must be added dynamically.</p>
<h3 id="heading-2-use-an-object-index-signature">2. Use an object index signature</h3>
<p>Occasionally, the properties of the object truly need to be added at a later time than when declared.</p>
<p>In this case, you can leverage the object index signature as follows:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">type</span> Org = {[key: <span class="hljs-built_in">string</span>] : <span class="hljs-built_in">string</span>}

<span class="hljs-keyword">const</span> organization: Org = {}

organization.name = <span class="hljs-string">"Freecodecamp"</span>
</code></pre>
<p>See the <a target="_blank" href="https://www.typescriptlang.org/play?#code/C4TwDgpgBA8gTgcygXigbwNoGsIgFxQDOwcAlgHYIC6UBxZlAvgFDMDGA9ucVB4gIblSAL37BSXAvCSo0LZnwSCRYieQB05fgFtoqAEQAxOBAicAJmZ1h9rO0A">TypeScript playground</a>.</p>
<p>At the time the <code>organization</code> variable is declared, you go ahead and explicitly type it to the following <code>{[key: string] : string}</code>.</p>
<p>To explain the syntax further, you might be used to object types having fixed property types:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">type</span> obj = {
  name: <span class="hljs-built_in">string</span>
}
</code></pre>
<p>But you can also substitute <code>name</code> for a “variable type”.</p>
<p>For example, if you want to define any string property on <code>obj</code>:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">type</span> obj = {
 [key: <span class="hljs-built_in">string</span>]: <span class="hljs-built_in">string</span>
}
</code></pre>
<p>Note that the syntax is similar to how you’d use a variable object property in standard JavaScript:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">const</span> variable = <span class="hljs-string">"name"</span> 

<span class="hljs-keyword">const</span> obj = {
   [variable]: <span class="hljs-string">"Freecodecamp"</span>
}
</code></pre>
<p>The TypeScript equivalent is called an object index signature.</p>
<p>Also, note that you could type <code>key</code> with other primitives:</p>
<pre><code class="lang-ts"><span class="hljs-comment">// number </span>
<span class="hljs-keyword">type</span> Org = {[key: <span class="hljs-built_in">number</span>] : <span class="hljs-built_in">string</span>}

<span class="hljs-comment">// string </span>
<span class="hljs-keyword">type</span> Org = {[key: <span class="hljs-built_in">string</span>] : <span class="hljs-built_in">string</span>}

<span class="hljs-comment">//boolean</span>
<span class="hljs-keyword">type</span> Org = {[key: <span class="hljs-built_in">boolean</span>] : <span class="hljs-built_in">string</span>}
</code></pre>
<h3 id="heading-3-use-the-record-utility-type">3. Use the Record utility type</h3>
<p>The solution here is quite concise:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">type</span> Org = Record&lt;<span class="hljs-built_in">string</span>, <span class="hljs-built_in">string</span>&gt;

<span class="hljs-keyword">const</span> organization: Org = {}


organization.name = <span class="hljs-string">"Freecodecamp"</span>
</code></pre>
<p>Instead of using a type alias, you can also inline the type:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">const</span> organization: Record&lt;<span class="hljs-built_in">string</span>, <span class="hljs-built_in">string</span>&gt; = {}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/image-82.png" alt="Image" width="600" height="400" loading="lazy">
<em>Using the Record utility type</em></p>
<p>See the <a target="_blank" href="https://www.typescriptlang.org/play?#code/C4TwDgpgBA8gTgcygXigJQgYwPZwCYA8AzsHAJYB2CANFCeVQHwBQzOFJUuCAhhWQC8ewMtgoAuWIhRQA3gF9Wzbn0HDRFAHQUeAW2ioARADE4ELNjxY9YQ0tZA">TypeScript playground</a>.</p>
<p>The <code>Record</code> utility type has the following signature: <code>Record&lt;Keys, Type&gt;</code>.</p>
<p>It allows you to constrict an object type whose properties are <code>Keys</code> and property values are <code>Type</code>.</p>
<p>In our example, <code>Keys</code> represents <code>string</code> and <code>Type</code>, <code>string</code> as well.</p>
<h2 id="heading-conclusion-4">Conclusion</h2>
<p>Apart from primitives, the most common types you’ll have to deal with are likely object types.</p>
<p>In cases where you need to build an object dynamically, take advantage of the Record utility type or use the object index signature to define the allowed properties on the object.</p>
<p>Note that you can get a <a target="_blank" href="https://www.ohansemmanuel.com/cheatsheet/top-7-stack-overflowed-typescript-questions">PDF or ePub</a>, version of this cheatsheet for easier reference, or for reading on your Kindle or tablet.</p>
<p>Thank you for reading!</p>
<h2 id="heading-fancy-a-free-typescript-book">Fancy a Free TypeScript Book?</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/image-78.png" alt="Image" width="600" height="400" loading="lazy">
<em>Build strongly typed Polymorphic React components book</em></p>
<p><a target="_blank" href="https://www.ohansemmanuel.com/books/how-to-build-strongly-typed-polymorphic-react-components">Get this book for free</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ 48 answers on StackOverflow to the most popular Angular questions ]]>
                </title>
                <description>
                    <![CDATA[ By Shlomi Levi I gathered the most common questions and answers from Stackoverflow. These questions were chosen by the highest score received. Whether you are an expert or a beginner, you can learn from others’ experiences. Table of Contents Angular... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/48-answers-on-stack-overflow-to-the-most-popular-angular-questions-52f9eb430ab0/</link>
                <guid isPermaLink="false">66c3416ba1d481faeda49ac1</guid>
                
                    <category>
                        <![CDATA[ Angular ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Stack Overflow ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Sun, 11 Mar 2018 12:13:18 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*TtrtAMfn2PATB_nD8YpeAA.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Shlomi Levi</p>
<p>I gathered the most common questions and answers from Stackoverflow. These questions were chosen by the highest score received. Whether you are an expert or a beginner, you can learn from others’ experiences.</p>
<h3 id="heading-table-of-contents">Table of Contents</h3>
<ul>
<li><a class="post-section-overview" href="#b4d0">Angular — Promise vs Observable</a></li>
<li><a class="post-section-overview" href="#d37e">Difference between Constructor and ngOnInit</a></li>
<li><a class="post-section-overview" href="#008f">Can’t bind to ‘ngModel’ since it isn’t a known property of ‘input’</a></li>
<li><a class="post-section-overview" href="#7e4b">Angular HTML binding</a></li>
<li><a class="post-section-overview" href="#22fe">Angular/RxJs When should I unsubscribe from <code>Subscription</code></a></li>
<li><a class="post-section-overview" href="#5251">How can I select an element in a component template?</a></li>
<li><a class="post-section-overview" href="#b510">What is the equivalent of ngShow and ngHide in Angular?</a></li>
<li><a class="post-section-overview" href="#76f3">How to bundle an Angular app for production</a></li>
<li><a class="post-section-overview" href="#9842">BehaviorSubject vs Observable?</a></li>
<li><a class="post-section-overview" href="#883d">@Directive v/s @Component in Angular</a></li>
<li><a class="post-section-overview" href="#4653">Angular HTTP GET with TypeScript error http.get(…).map is not a function in [null]</a></li>
<li><a class="post-section-overview" href="#9c12">How to use jQuery with Angular?</a></li>
<li><a class="post-section-overview" href="#2739">Angular EXCEPTION: No provider for Http</a></li>
<li><a class="post-section-overview" href="#b612">Can’t bind to ‘formGroup’ since it isn’t a known property of ‘form’</a></li>
<li><a class="post-section-overview" href="#ce7e">Angular DI Error — EXCEPTION: Can’t resolve all parameters</a></li>
<li><a class="post-section-overview" href="#1761">Angular — Set headers for every request</a></li>
<li><a class="post-section-overview" href="#cace">How to use *ngIf else in Angular?</a></li>
<li><a class="post-section-overview" href="#92c6">Angular no provider for NameService</a></li>
<li><a class="post-section-overview" href="#bc7c">Binding select element to object in Angular</a></li>
<li><a class="post-section-overview" href="#e423">What is difference between declarations, providers and import in NgModule</a></li>
<li><a class="post-section-overview" href="#d774">In Angular, how do you determine the active route?</a></li>
<li><a class="post-section-overview" href="#17bd">Angular CLI SASS options</a></li>
<li><a class="post-section-overview" href="#83b6">Triggering change detection manually in Angular</a></li>
<li><a class="post-section-overview" href="#eb6d">Angular and Typescript: Can’t find names</a></li>
<li><a class="post-section-overview" href="#c874">Angular — What is the meanings of module.id in component?</a></li>
<li><a class="post-section-overview" href="#831b">How can I get new selection in “select” in Angular 2?</a></li>
<li><a class="post-section-overview" href="#aad5">Angular exception: Can’t bind to ‘ngForIn’ since it isn’t a known native property</a></li>
<li><a class="post-section-overview" href="#1556"><em>ngIf and </em>ngFor on same element causing error</a></li>
<li><a class="post-section-overview" href="#a331">What is the Angular equivalent to an AngularJS $watch?</a></li>
<li><a class="post-section-overview" href="#7a78">Importing lodash into angular2 + typescript application</a></li>
<li><a class="post-section-overview" href="#5b1c">How to detect a route change in Angular?</a></li>
<li><a class="post-section-overview" href="#869e">Global Events in Angular</a></li>
<li><a class="post-section-overview" href="#e7f2">What are differences between SystemJS and Webpack?</a></li>
<li><a class="post-section-overview" href="#176d">Angular: Can’t find Promise, Map, Set and Iterator</a></li>
<li><a class="post-section-overview" href="#2459">Angular RC4 — Angular ^2.0.0 with Typescript 2.0.0</a></li>
<li><a class="post-section-overview" href="#6188">How to detect when an @Input() value changes in Angular?</a></li>
<li><a class="post-section-overview" href="#d2d3">How to pass url arguments (query string) to a HTTP request on Angular</a></li>
<li><a class="post-section-overview" href="#57cd">How do you deploy Angular apps?</a></li>
<li><a class="post-section-overview" href="#fb28">ngFor with index as value in attribute</a></li>
<li><a class="post-section-overview" href="#c709">Define global constants in Angular 2</a></li>
<li><a class="post-section-overview" href="#7910">Angular — Use pipes in services and components</a></li>
<li><a class="post-section-overview" href="#1cef">Angular2 Exception: Can’t bind to ‘routerLink’ since it isn’t a known native property</a></li>
<li><a class="post-section-overview" href="#4d6c">Angular 2 dynamic tabs with user-click chosen components</a></li>
<li><a class="post-section-overview" href="#4f96">Delegation: EventEmitter or Observable in Angular</a></li>
<li><a class="post-section-overview" href="#bcef">How to add bootstrap to an angular-cli project</a></li>
<li><a class="post-section-overview" href="#d3fa">access key and value of object using *ngFor</a></li>
<li><a class="post-section-overview" href="#3f0e">Angular exception: Can’t bind to ‘ngFor’ since it isn’t a known native property</a></li>
<li><a class="post-section-overview" href="#7f27">How to add font-awesome to Angular 2 + CLI project</a></li>
<li><a class="post-section-overview" href="#54eb">Difference between HTTP and HTTPClient in angular 4?</a></li>
</ul>
<p><strong>Enjoy!</strong></p>
<h3 id="heading-angular-promise-vs-observable">Angular — Promise vs Observable</h3>
<blockquote>
<p>551+ points _? 1<em>50,497+ viewed   
</em><strong><a target="_blank" href="https://stackoverflow.com/users/6364715/rohit">Rohit</a> asked,</strong>_</p>
</blockquote>
<p>Can someone please explain the difference between <code>Promise</code> and <code>Observable</code> in Angular?</p>
<p>An example on each would be helpful in understanding both the cases. In what scenario can we use each case?</p>
<blockquote>
<p><a target="_blank" href="https://stackoverflow.com/users/217408"><strong><em>Günter Zöchbauer</em></strong></a> <strong><em>answered, (686+ points)</em></strong></p>
</blockquote>
<p><strong>Promise</strong></p>
<p>A <code>Promise</code> handles a <strong>single event</strong> when an async operation completes or fails.</p>
<p>Note: There are <code>Promise</code> libraries out there that support cancellation, but ES6 <code>Promise</code> doesn't so far.</p>
<p><strong>Observable</strong></p>
<p>An <code>Observable</code> is like a <code>**Stream**</code> (in many languages) and allows to pass zero or more events where the callback is called for each event.</p>
<p>Often <code>Observable</code> is preferred over <code>Promise</code> because it provides the features of <code>Promise</code> and more. With <code>Observable</code> it doesn't matter if you want to handle 0, 1, or multiple events. You can utilize the same API in each case.</p>
<p><code>Observable</code> also has the advantage over <code>Promise</code> to be <strong>cancelable</strong>. If the result of an HTTP request to a server or some other expensive async operation isn't needed anymore, the <code>Subscription</code> of an <code>Observable</code> allows to cancel the subscription, while a <code>Promise</code> will eventually call the success or failed callback even when you don't need the notification or the result it provides anymore.</p>
<p>Observable provides <strong>operators</strong> like <code>map</code>, <code>forEach</code>, <code>reduce</code>, ... similar to an array</p>
<p>There are also powerful operators like <code>retry()</code>, or <code>replay()</code>, ... that are often quite handy.</p>
<p><a target="_blank" href="https://stackoverflow.com/questions/37364973"><strong>Source</strong></a><br><strong><a class="post-section-overview" href="#599b">Top</a></strong></p>
<h3 id="heading-difference-between-constructor-and-ngoninit">Difference between Constructor and ngOnInit</h3>
<blockquote>
<p>444+ points _? 1<em>90,166+ viewed   
</em><strong><a target="_blank" href="https://stackoverflow.com/users/4029338/haseena-p-a">Haseena P A</a> asked,</strong>_</p>
</blockquote>
<p>Angular provides lifecycle hook <code>ngOnInit</code> by default.</p>
<p>Why should <code>ngOnInit</code> be used, if we already have a <code>constructor</code>?</p>
<blockquote>
<p><a target="_blank" href="https://stackoverflow.com/users/5043867"><strong><em>Pardeep Jain</em></strong></a> <strong><em>answered, (512+ points)</em></strong></p>
</blockquote>
<p>The <code>Constructor</code> is a default method of the class that is executed when the class is instantiated and ensures proper initialization of fields in the class and its subclasses. Angular or better Dependency Injector (DI) analyzes the constructor parameters and when it creates a new instance by calling <code>new MyClass()</code> it tries to find providers that match the types of the constructor parameters, resolves them and passes them to the constructor like</p>
<pre><code class="lang-js"><span class="hljs-keyword">new</span> MyClass(someArg);
</code></pre>
<p><code>ngOnInit</code> is a lifecycle hook called by Angular2 to indicate that Angular is done creating the component.</p>
<p>We have to import <code>OnInit</code> in order to use like this (actually implementing <code>OnInit</code> is not mandatory but considered good practice):</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> {Component, OnInit} <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;
</code></pre>
<p>then to use the method of <code>OnInit</code> we have to implement in the class like this.</p>
<pre><code class="lang-js"><span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">App</span> <span class="hljs-title">implements</span> <span class="hljs-title">OnInit</span></span>{
  <span class="hljs-keyword">constructor</span>(){
     <span class="hljs-comment">//called first time before the ngOnInit()</span>
  }

  ngOnInit(){
     <span class="hljs-comment">//called after the constructor and called  after the first ngOnChanges() </span>
  }
}
</code></pre>
<p><code>Implement this interface to execute custom initialization logic after your directive's data-bound properties have been initialized. ngOnInit is called right after the directive's data-bound properties have been checked for the first time, and before any of its children have been checked. It is invoked only once when the directive is instantiated.</code></p>
<p>Mostly we use <code>ngOnInit</code> for all the initialization/declaration and avoid stuff to work in the constructor. The constructor should only be used to initialize class members but shouldn't do actual "work".</p>
<p>So you should use <code>constructor()</code> to setup Dependency Injection and not much else. ngOnInit() is better place to "start" - it's where/when components' bindings are resolved.</p>
<p>For more information refer here:</p>
<ul>
<li><a target="_blank" href="https://angular.io/api/core/OnInit">https://angular.io/api/core/OnInit</a></li>
<li><a target="_blank" href="https://stackoverflow.com/a/35846307/5043867">Angular 2 Component Constructor Vs OnInit</a></li>
</ul>
<p><a target="_blank" href="https://stackoverflow.com/questions/35763730"><strong>Source</strong></a><br><strong><a class="post-section-overview" href="#599b">Top</a></strong></p>
<h3 id="heading-cant-bind-to-ngmodel-since-it-isnt-a-known-property-of-input">Can’t bind to ‘ngModel’ since it isn’t a known property of ‘input’</h3>
<blockquote>
<p>442+ points _? 2<em>46,901+ viewed   
</em><strong><a target="_blank" href="https://stackoverflow.com/users/3433751/anthony-breneli%C3%A8re">abreneliere</a> asked,</strong>_</p>
</blockquote>
<p>I’ve got the following error when launching my Angular app, even if the component is not displayed.</p>
<p>I have to comment out the so that my app works.</p>
<pre><code class="lang-bash">zone.js:461 Unhandled Promise rejection: Template parse errors:
Can<span class="hljs-string">'t bind to '</span>ngModel<span class="hljs-string">' since it isn'</span>t a known property of <span class="hljs-string">'input'</span>. (<span class="hljs-string">"
    &lt;div&gt;
        &lt;label&gt;Created:&lt;/label&gt;
        &lt;input  type="</span>text<span class="hljs-string">" [ERROR -&gt;][(ngModel)]="</span><span class="hljs-built_in">test</span><span class="hljs-string">" placeholder="</span>foo<span class="hljs-string">" /&gt;
    &lt;/div&gt;
&lt;/div&gt;"</span>): InterventionDetails@4:28 ; Zone: &lt;root&gt; ; Task: Promise.then ; Value:
</code></pre>
<p>I’m looking at the Hero plucker but I don’t see any difference.</p>
<p>Here is the component file:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { Component, EventEmitter, Input, OnInit, Output } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;
<span class="hljs-keyword">import</span> { Intervention } <span class="hljs-keyword">from</span> <span class="hljs-string">'../../model/intervention'</span>;

@Component({
    <span class="hljs-attr">selector</span>: <span class="hljs-string">'intervention-details'</span>,
    <span class="hljs-attr">templateUrl</span>: <span class="hljs-string">'app/intervention/details/intervention.details.html'</span>,
    <span class="hljs-attr">styleUrls</span>: [<span class="hljs-string">'app/intervention/details/intervention.details.css'</span>]
})

<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">InterventionDetails</span>
</span>{
    @Input() intervention: Intervention;
    public test : string = <span class="hljs-string">"toto"</span>;
}
</code></pre>
<blockquote>
<p><a target="_blank" href="https://stackoverflow.com/users/3433751"><strong><em>abreneliere</em></strong></a> <strong><em>answered, (674+ points)</em></strong></p>
</blockquote>
<p>Yes that’s it, in the app.module.ts, I just added :</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { FormsModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/forms'</span>;

[...]

@NgModule({
  <span class="hljs-attr">imports</span>: [
    [...]
    FormsModule
  ],
  [...]
})
</code></pre>
<p><a target="_blank" href="https://stackoverflow.com/questions/38892771"><strong>Source</strong></a><br><strong><a class="post-section-overview" href="#599b">Top</a></strong></p>
<h3 id="heading-angular-html-binding">Angular HTML binding</h3>
<blockquote>
<p>385+ points _? 2<em>27,115+ viewed   
</em><strong><a target="_blank" href="https://stackoverflow.com/users/3433751/anthony-breneli%C3%A8re">Aviad P.</a> asked,</strong>_</p>
</blockquote>
<p>I am writing an Angular application, and I have an HTML response I want to display. How do I do that? If I simply use the binding syntax <code>{{myVal}}</code> it encodes all HTML characters (of course).</p>
<p>I need somehow to bind the inner html of a div to the variable value.</p>
<blockquote>
<p><a target="_blank" href="https://stackoverflow.com/users/427763"><strong><em>prolink007</em></strong></a> <strong><em>answered, (691+ points)</em></strong></p>
</blockquote>
<p>The correct syntax is now the following:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> [<span class="hljs-attr">innerHTML</span>]=<span class="hljs-string">"theHtmlString"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>Working in <code>5.2.6</code></p>
<p><a target="_blank" href="https://angular.io/docs/ts/latest/guide/template-syntax.html#!#property-binding-or-interpolation-">Documentation Reference</a></p>
<p><a target="_blank" href="https://stackoverflow.com/questions/31548311"><strong>Source</strong></a><br><strong><a class="post-section-overview" href="#599b">Top</a></strong></p>
<h3 id="heading-angularrxjs-when-should-i-unsubscribe-from-subscription">Angular/RxJs When should I unsubscribe from <code>Subscription</code></h3>
<blockquote>
<p>320+ points _? 6<em>9,606+ viewed   
</em><strong><a target="_blank" href="https://stackoverflow.com/users/1429493/sergey-tihon">Sergey Tihon</a> asked,</strong>_</p>
</blockquote>
<p>When should I store the <code>Subscription</code> instances and invoke <code>unsubscribe()</code> during the NgOnDestroy lifecycle and when can I simply ignore them?</p>
<p>Saving all subscriptions introduces a lot of mess into component code.</p>
<p><a target="_blank" href="https://angular.io/docs/ts/latest/guide/server-communication.html">HTTP Client Guide</a> ignore subscriptions like this:</p>
<pre><code class="lang-js">getHeroes() {
  <span class="hljs-built_in">this</span>.heroService.getHeroes()
                   .subscribe(
                     <span class="hljs-function"><span class="hljs-params">heroes</span> =&gt;</span> <span class="hljs-built_in">this</span>.heroes = heroes,
                     <span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span>  <span class="hljs-built_in">this</span>.errorMessage = <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">any</span>&gt;</span>error);
}</span>
</code></pre>
<p>In the same time <a target="_blank" href="https://angular.io/docs/ts/latest/guide/router.html">Route &amp; Navigation Guide</a> says that:</p>
<p><code>Eventually, we'll navigate somewhere else. The router will remove this component from the DOM and destroy it. We need to clean up after ourselves before that happens. Specifically, we must unsubscribe before Angular destroys the component. Failure to do so could create a memory leak.</code></p>
<p><code>We unsubscribe from our Observable in the ngOnDestroy method.</code></p>
<pre><code class="lang-js">private sub: any;

ngOnInit() {
  <span class="hljs-built_in">this</span>.sub = <span class="hljs-built_in">this</span>.route.params.subscribe(<span class="hljs-function"><span class="hljs-params">params</span> =&gt;</span> {
     <span class="hljs-keyword">let</span> id = +params[<span class="hljs-string">'id'</span>]; <span class="hljs-comment">// (+) converts string 'id' to a number</span>
     <span class="hljs-built_in">this</span>.service.getHero(id).then(<span class="hljs-function"><span class="hljs-params">hero</span> =&gt;</span> <span class="hljs-built_in">this</span>.hero = hero);
   });
}

ngOnDestroy() {
  <span class="hljs-built_in">this</span>.sub.unsubscribe();
}
</code></pre>
<blockquote>
<p><a target="_blank" href="https://stackoverflow.com/users/939634"><strong><em>seangwright</em></strong></a> <strong><em>answered, (508+ points)</em></strong></p>
</blockquote>
<h4 id="heading-edit-3-the-official-solution-20170409">— — Edit 3 — The ‘Official’ Solution (2017/04/09)</h4>
<p>I spoke with Ward Bell about this question at NGConf (I even showed him this answer which he said was correct) but he told me the docs team for Angular had a solution to this question that is unpublished (though they are working on getting it approved). He also told me I could update my SO answer with the forthcoming official recommendation.</p>
<p>The solution we should all use going forward is to add a <code>private ngUnsubscribe: Subject = new Subject();</code> field to all components that have <code>.subscribe()</code> calls to <code>Observable</code>s within their class code.</p>
<p>We then call <code>this.ngUnsubscribe.next(); this.ngUnsubscribe.complete();</code> in our <code>ngOnDestroy()</code> methods.</p>
<p>The secret sauce (as noted already by <a target="_blank" href="https://stackoverflow.com/a/42695571/939634">@metamaker</a>) is to call <code>.takeUntil(this.ngUnsubscribe)</code> before each of our <code>.subscribe()</code> calls which will guarantee all subscriptions will be cleaned up when the component is destroyed.</p>
<p>Example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { Component, OnDestroy, OnInit } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'rxjs/add/operator/takeUntil'</span>;
<span class="hljs-comment">// import { takeUntil } from 'rxjs/operators'; // for rxjs ^5.5.0 lettable operators</span>
<span class="hljs-keyword">import</span> { Subject } <span class="hljs-keyword">from</span> <span class="hljs-string">'rxjs/Subject'</span>;

<span class="hljs-keyword">import</span> { MyThingService } <span class="hljs-keyword">from</span> <span class="hljs-string">'../my-thing.service'</span>;

@Component({
    <span class="hljs-attr">selector</span>: <span class="hljs-string">'my-thing'</span>,
    <span class="hljs-attr">templateUrl</span>: <span class="hljs-string">'./my-thing.component.html'</span>
})
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyThingComponent</span> <span class="hljs-title">implements</span> <span class="hljs-title">OnDestroy</span>, <span class="hljs-title">OnInit</span> </span>{
    private ngUnsubscribe: Subject = <span class="hljs-keyword">new</span> Subject();

    <span class="hljs-keyword">constructor</span>(
        private myThingService: MyThingService,
    ) { }

    ngOnInit() {
        <span class="hljs-built_in">this</span>.myThingService.getThings()
            .takeUntil(<span class="hljs-built_in">this</span>.ngUnsubscribe)
            .subscribe(<span class="hljs-function"><span class="hljs-params">things</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(things));

        <span class="hljs-comment">/* if using lettable operators in rxjs ^5.5.0
        this.myThingService.getThings()
            .pipe(takeUntil(this.ngUnsubscribe))
            .subscribe(things =&gt; console.log(things));
        */</span>

        <span class="hljs-built_in">this</span>.myThingService.getOtherThings()
            .takeUntil(<span class="hljs-built_in">this</span>.ngUnsubscribe)
            .subscribe(<span class="hljs-function"><span class="hljs-params">things</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(things));

    }

    ngOnDestroy() {
        <span class="hljs-built_in">this</span>.ngUnsubscribe.next();
        <span class="hljs-built_in">this</span>.ngUnsubscribe.complete();
    }
}
</code></pre>
<h4 id="heading-edit-2-20161228">— — Edit 2 (2016/12/28)</h4>
<p><strong>Source 5</strong></p>
<p>The Angular tutorial, the Routing chapter now states the following: “The Router manages the observables it provides and localizes the subscriptions. The subscriptions are cleaned up when the component is destroyed, protecting against memory leaks, so we don’t need to unsubscribe from the route params Observable.” — <a target="_blank" href="https://stackoverflow.com/questions/38008334/angular2-rxjs-when-should-i-unsubscribe-from-subscription/41177163?noredirect=1#comment69909721_41177163">Mark Rajcok</a></p>
<p>Here’s a <a target="_blank" href="https://github.com/angular/angular.io/issues/3003#issuecomment-268429065">discussion</a> on the Github issues for the Angular docs regarding Router Observables where Ward Bell mentions that clarification for all of this is in the works.</p>
<h4 id="heading-edit-1">— — Edit 1</h4>
<p><strong>Source 4</strong></p>
<p>In this <a target="_blank" href="https://youtu.be/WWR9nxVx1ec?t=20m32s">video from NgEurope</a> Rob Wormald also says you do not need to unsubscribe from Router Observables. He also mentions the <code>http</code> service and <code>ActivatedRoute.params</code> in this <a target="_blank" href="https://youtu.be/VLGCCpOWFFw?t=33m37s">video from November 2016</a>.</p>
<h4 id="heading-original-answer">— — Original Answer</h4>
<p><strong>TLDR:</strong></p>
<p>For this question there are (2) kinds of <code>Observables</code> - <strong>finite</strong> value and <strong>infinite</strong> value.</p>
<p><code>http</code> <code>Observables</code> produce <strong>finite</strong> (1) values and something like a DOM <code>event listener</code> <code>Observables</code> produce <strong>infinite</strong> values.</p>
<p>If you manually call <code>subscribe</code> (not using async pipe), then <code>unsubscribe</code> from <strong>infinite</strong> <code>Observables</code>.</p>
<p>Don’t worry about <strong>finite</strong> ones, <code>RxJs</code> will take care of them.</p>
<p><strong>Source 1</strong></p>
<p>I tracked down an answer from Rob Wormald in Angular’s Gitter <a target="_blank" href="https://gitter.im/angular/angular?at=5681e8fa3c68940269251fa5">here</a>.</p>
<p>He states (i reorganized for clarity and emphasis is mine)</p>
<p><code>if it's **a single-value-sequence** (like an http request) the **manual cleanup is unnecessary** (assuming you subscribe in the controller manually)</code></p>
<p><code>i should say "if it's a **sequence that completes**" (of which single value sequences, a la http, are one)</code></p>
<p><code>**if it's an infinite sequence**, **you should unsubscribe** which the async pipe does for you</code></p>
<p>Also he mentions in this <a target="_blank" href="https://youtu.be/UHI0AzD_WfY?t=26m42s">youtube video</a> on Observables that <code>they clean up after themselves</code>... in the context of Observables that <code>complete</code> (like Promises, which always complete because they are always producing 1 value and ending - we never worried about unsubscribing from Promises to make sure they clean up <code>xhr</code> event listeners, right?).</p>
<p><strong>Source 2</strong></p>
<p>Also in the <a target="_blank" href="https://angular-2-training-book.rangle.io/handout/observables/disposing_subscriptions_and_releasing_resources.html">Rangle guide to Angular 2</a> it reads</p>
<p><code>In most cases we will not need to explicitly call the unsubscribe method unless we want to cancel early or our Observable has a longer lifespan than our subscription. The default behavior of Observable operators is to dispose of the subscription as soon as .complete() or .error() messages are published. Keep in mind that RxJS was designed to be used in a "fire and forget" fashion most of the time.</code></p>
<p>When does the phrase <code>our Observable has a longer lifespan than our subscription</code> apply?</p>
<p>It applies when a subscription is created inside a component which is destroyed before (or not ‘long’ before) the <code>Observable</code> completes.</p>
<p>I read this as meaning if we subscribe to an <code>http</code> request or an observable that emits 10 values and our component is destroyed before that <code>http</code> request returns or the 10 values have been emitted, we are still ok!</p>
<p>When the request does return or the 10th value is finally emitted the <code>Observable</code> will complete and all resources will be cleaned up.</p>
<p><strong>Source 3</strong></p>
<p>If we look at <a target="_blank" href="https://angular-2-training-book.rangle.io/handout/routing/routeparams.html">this example</a> from the same Rangle guide we can see that the <code>Subscription</code> to <code>route.params</code> does require an <code>unsubscribe()</code> because we don't know when those <code>params</code> will stop changing (emitting new values).</p>
<p>The component could be destroyed by navigating away in which case the route params will likely still be changing (they could technically change until the app ends) and the resources allocated in subscription would still be allocated because there hasn’t been a <code>completion</code>.</p>
<p><a target="_blank" href="https://stackoverflow.com/questions/38008334"><strong>Source</strong></a><br><strong><a class="post-section-overview" href="#599b">Top</a></strong></p>
<h3 id="heading-how-can-i-select-an-element-in-a-component-template">How can I select an element in a component template?</h3>
<blockquote>
<p>263+ points _? 2<em>65,966+ viewed   
</em><strong><a target="_blank" href="https://stackoverflow.com/users/2748475/aman-gupta">Aman Gupta</a> asked,</strong>_</p>
</blockquote>
<p>Does anybody know how to get hold of an element defined in a component template? Polymer makes it really easy with the <code>$</code> and <code>$$</code>.</p>
<p>I was just wondering how to go about it in Angular.</p>
<p>Take the example from the tutorial:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> {Component} <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>

@Component({
    <span class="hljs-attr">selector</span>:<span class="hljs-string">'display'</span>
    <span class="hljs-attr">template</span>:<span class="hljs-string">`
     &lt;input #myname(input)="updateName(myname.value)"/&gt;
     &lt;p&gt;My name : {{myName}}&lt;/p&gt;
    `</span>

})
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DisplayComponent</span> </span>{
    <span class="hljs-attr">myName</span>: string = <span class="hljs-string">"Aman"</span>;
    updateName(input: <span class="hljs-built_in">String</span>) {
        <span class="hljs-built_in">this</span>.myName = input;
    }
}
</code></pre>
<p>How do I catch hold of a reference of the <code>p</code> or <code>input</code> element from within the class definition?</p>
<blockquote>
<p><a target="_blank" href="https://stackoverflow.com/users/1413538"><strong><em>Brocco</em></strong></a> <strong><em>answered, (149+ points)</em></strong></p>
</blockquote>
<p>You can get a handle to the DOM element via <code>ElementRef</code> by injecting it into your component's constructor:</p>
<pre><code class="lang-js"><span class="hljs-keyword">constructor</span>(myElement: ElementRef) { ... }
</code></pre>
<p>Docs: <a target="_blank" href="https://angular.io/docs/ts/latest/api/core/index/ElementRef-class.html">https://angular.io/docs/ts/latest/api/core/index/ElementRef-class.html</a></p>
<p><a target="_blank" href="https://stackoverflow.com/questions/32693061"><strong>Source</strong></a><br><strong><a class="post-section-overview" href="#599b">Top</a></strong></p>
<h3 id="heading-what-is-the-equivalent-of-ngshow-and-nghide-in-angular">What is the equivalent of ngShow and ngHide in Angular?</h3>
<blockquote>
<p>261+ points _? 2<em>06,651+ viewed<br><strong><a target="_blank" href="https://stackoverflow.com/users/2870735/mihai-r%C4%83ducanu">Mihai Răducanu</a></strong> </em><strong>asked,</strong>_</p>
</blockquote>
<p>I have a number of elements that I want to be visible under certain conditions.</p>
<p>In AngularJS I would write</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">ng-show</span>=<span class="hljs-string">"myVar"</span>&gt;</span>stuff<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>How can I do this in Angular?</p>
<blockquote>
<p><a target="_blank" href="https://stackoverflow.com/users/217408"><strong><em>Günter Zöchbauer</em></strong></a> <strong><em>answered, (445+ points)</em></strong></p>
</blockquote>
<p>Just bind to the <code>hidden</code> property</p>
<pre><code class="lang-html">[hidden]="!myVar"
</code></pre>
<p>See also</p>
<ul>
<li><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/hidden">https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/hidden</a></li>
</ul>
<p><strong>issues</strong></p>
<p><code>hidden</code> has some issues though because it can conflict with CSS for the <code>display</code> property.</p>
<p>See how <code>some</code> in <a target="_blank" href="https://plnkr.co/edit/SO3c3UUT3LBvhNAeriCz?p=preview"><strong>Plunker example</strong></a> doesn't get hidden because it has a style</p>
<pre><code class="lang-css"><span class="hljs-selector-pseudo">:host</span> {<span class="hljs-attribute">display</span>: block;}
</code></pre>
<p>set. (This might behave differently in other browsers — I tested with Chrome 50)</p>
<p><strong>workaround</strong></p>
<p>You can fix it by adding</p>
<pre><code class="lang-css"><span class="hljs-selector-attr">[hidden]</span> { <span class="hljs-attribute">display</span>: none <span class="hljs-meta">!important</span>;}
</code></pre>
<p>To a global style in <code>index.html</code>.</p>
<p><strong>another pitfall</strong></p>
<pre><code class="lang-html">hidden="false"
hidden="{{false}}"
hidden="{{isHidden}}" // isHidden = false;
</code></pre>
<p>are the same as</p>
<pre><code class="lang-html">hidden="true"
</code></pre>
<p>and will not show the element.</p>
<p><code>hidden="false"</code> will assign the string <code>"false"</code> which is considered truthy.<br>Only the value <code>false</code> or removing the attribute will actually make the element visible.</p>
<p>Using <code>{{}}</code> also converts the expression to a string and won't work as expected.</p>
<p>Only binding with <code>[]</code> will work as expected because this <code>false</code> is assigned as <code>false</code> instead of <code>"false"</code>.</p>
<p><code>***ngIf**</code> <strong>vs <code>[hidden]</code></strong></p>
<p><code>*ngIf</code> effectively removes its content from the DOM while <code>[hidden]</code> modifies the <code>display</code> property and only instructs the browser to not show the content but the DOM still contains it.</p>
<p><a target="_blank" href="https://stackoverflow.com/questions/35578083"><strong>Source</strong></a><br><strong><a class="post-section-overview" href="#599b">Top</a></strong></p>
<h3 id="heading-how-to-bundle-an-angular-app-for-production">How to bundle an Angular app for production</h3>
<blockquote>
<p>258+ points _? 1<em>11,603+ viewed   
</em><strong><a target="_blank" href="https://stackoverflow.com/users/4155124/pat-m">Pat M</a> asked,</strong>_</p>
</blockquote>
<p>I would like to track and update in this thread the latest best (and hopefully the simplest) method to bundle Angular (version 2, 4, …) for production on a live web server.</p>
<p>Please include the Angular version within answers so we can track better when it moves to later releases.</p>
<blockquote>
<p><a target="_blank" href="https://stackoverflow.com/users/1630604"><strong><em>Nicolas Henneaux</em></strong></a> <strong><em>answered, (267+ points)</em></strong></p>
</blockquote>
<h4 id="heading-2x-4x-5x-typescript-with-angular-cli"><code>2.x, 4.x, 5.x</code> (TypeScript) with Angular CLI</h4>
<h4 id="heading-onetime-setup">OneTime Setup</h4>
<ul>
<li><code>npm install -g @angular/cli</code></li>
<li><code>ng new projectFolder</code> creates a new application</li>
</ul>
<h4 id="heading-bundling-step">Bundling Step</h4>
<ul>
<li><code>ng build --prod</code> (run in command line when directory is <code>projectFolder</code>)</li>
<li><em>flag <code>prod</code> bundle for production (see the <a target="_blank" href="https://github.com/angular/angular-cli/wiki/build#--dev-vs---prod-builds">Angular documentation</a> for the list of option included with the production flag).</em></li>
<li>Compress using <a target="_blank" href="https://en.wikipedia.org/wiki/Brotli">Brotli compression</a> the resources using the following command<code>for i in dist/*; do brotli $i; done</code></li>
</ul>
<p><em>bundles are generated by default to <strong>projectFolder/dist/</strong></em></p>
<h4 id="heading-output">Output</h4>
<p><em>Sizes with Angular <code>5.2.8</code> with CLI <code>1.7.2</code></em></p>
<ul>
<li><code>dist/main.[hash].bundle.js</code> Your application bundled [ size: 151 KB for new Angular CLI application empty, <strong>36 KB</strong> compressed].</li>
<li><code>dist/polyfill.[hash].bundle.js</code> the polyfill dependencies (@angular, RxJS...) bundled [ size: 58 KB for new Angular CLI application empty, <strong>17 KB</strong> compressed].</li>
<li><code>dist/index.html</code> entry point of your application.</li>
<li><code>dist/inline.[hash].bundle.js</code> webpack loader</li>
<li><code>dist/style.[hash].bundle.css</code> the style definitions</li>
<li><code>dist/assets</code> resources copied from the Angular CLI assets configuration</li>
</ul>
<h4 id="heading-deployment">Deployment</h4>
<p>You can get a preview of your application using the <code>ng serve --prod</code> command that starts a local HTTP server such that the application with production files is accessible using <a target="_blank" href="http://localhost:4200">http://localhost:4200</a>.</p>
<p>For a production usage, you have to deploy all the files from the <code>dist</code> folder in the HTTP server of your choice.</p>
<p><a target="_blank" href="https://stackoverflow.com/questions/37631098"><strong>Source</strong></a><br><strong><a class="post-section-overview" href="#599b">Top</a></strong></p>
<h3 id="heading-behaviorsubject-vs-observable">BehaviorSubject vs Observable?</h3>
<blockquote>
<p>250+ points _? 1<em>22,248+ viewed   
</em><strong><a target="_blank" href="https://stackoverflow.com/users/6620551/kevin-mark">Kevin Mark</a> asked,</strong>_</p>
</blockquote>
<p>I’m looking into Angular RxJs patterns and I don’t understand the difference between a BehaviorSubject and an Observable.</p>
<p>From my understanding, a BehaviorSubject is a value that can change over time (can be subscribed to and subscribers can receive updated results). This seems to be the exact same purpose of an Observable.</p>
<p>When would you use an Observable vs a BehaviorSubject? Are there benefits to using a BehaviorSubject over an Observable or vice versa?</p>
<blockquote>
<p><a target="_blank" href="https://stackoverflow.com/users/3070452"><strong><em>Shantanu Bhadoria</em></strong></a> <strong><em>answered, (425+ points)</em></strong></p>
</blockquote>
<p>BehaviorSubject is a type of subject, a subject is a special type of observable so you can subscribe to messages like any other observable. The unique features of BehaviorSubject are:</p>
<ul>
<li>It needs an initial value as it must always return a value on subscription even if it hasn’t received a <code>next()</code></li>
<li>Upon subscription it returns the last value of the subject. A regular observable only triggers when it receives an <code>onnext</code></li>
<li>at any point you can retrieve the last value of the subject in a non-observable code using the <code>getValue()</code> method.</li>
</ul>
<p>Unique features of a subject compared to an observable are:</p>
<ul>
<li>It is an observer in addition to being an observable so you can also send values to a subject in addition to subscribing to it.</li>
</ul>
<p>In addition you can get an observable from behavior subject using the <code>asobservable()</code> method on BehaviorSubject.</p>
<p>Observable is a Generic, and BehaviorSubject is technically a sub-type of Observable because BehaviorSubject is an observable with specific qualities.</p>
<p>Example with BehaviorSubject:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Behavior Subject</span>

<span class="hljs-comment">// a is an initial value. if there is a subscription </span>
<span class="hljs-comment">// after this, it would get "a" value immediately</span>
<span class="hljs-keyword">let</span> bSubject = <span class="hljs-keyword">new</span> BehaviorSubject(<span class="hljs-string">"a"</span>); 

bSubject.next(<span class="hljs-string">"b"</span>);

bSubject.subscribe(<span class="hljs-function">(<span class="hljs-params">value</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Subscription got"</span>, value); <span class="hljs-comment">// Subscription got b, </span>
                                          <span class="hljs-comment">// ^ This would not happen </span>
                                          <span class="hljs-comment">// for a generic observable </span>
                                          <span class="hljs-comment">// or generic subject by default</span>
});

bSubject.next(<span class="hljs-string">"c"</span>); <span class="hljs-comment">// Subscription got c</span>
bSubject.next(<span class="hljs-string">"d"</span>); <span class="hljs-comment">// Subscription got d</span>
</code></pre>
<p>Example 2 with regular subject:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Regular Subject</span>

<span class="hljs-keyword">let</span> subject = <span class="hljs-keyword">new</span> Subject(); 

subject.next(<span class="hljs-string">"b"</span>);

subject.subscribe(<span class="hljs-function">(<span class="hljs-params">value</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Subscription got"</span>, value); <span class="hljs-comment">// Subscription wont get </span>
                                          <span class="hljs-comment">// anything at this point</span>
});

subject.next(<span class="hljs-string">"c"</span>); <span class="hljs-comment">// Subscription got c</span>
subject.next(<span class="hljs-string">"d"</span>); <span class="hljs-comment">// Subscription got d</span>
</code></pre>
<p>An observable can be created from both Subject and BehaviorSubject using <code>subject.asobservable()</code>. Only difference being you can't send values to an observable using <code>next()</code> method.</p>
<p>In Angular services, I would use BehaviorSubject for a data service as a angular service often initializes before component and behavior subject ensures that the component consuming the service receives the last updated data even if there are no new updates since the component’s subscription to this data.</p>
<p><a target="_blank" href="https://stackoverflow.com/questions/39494058"><strong>Source</strong></a><br><strong><a class="post-section-overview" href="#599b">Top</a></strong></p>
<h3 id="heading-directive-vs-component-in-angular">@Directive v/s @Component in Angular</h3>
<blockquote>
<p>239+ points _? 6<em>1,582+ viewed   
</em><a target="_blank" href="https://stackoverflow.com/users/4917853/prasanjit-dey"><strong>Prasanjit Dey</strong></a> <strong>asked,</strong>_</p>
</blockquote>
<p>What is the difference between <code>@Component</code> and <code>@Directive</code> in Angular? Both of them seem to do the same task and have the same attributes.</p>
<p>What are the use cases and when to prefer one over another?</p>
<blockquote>
<p><a target="_blank" href="https://stackoverflow.com/users/1771017"><strong><em>jaker</em></strong></a> <strong><em>answered, (327+ points)</em></strong></p>
</blockquote>
<p><strong>A @Component requires a view whereas a @Directive does not.</strong></p>
<h3 id="heading-directives">Directives</h3>
<p>I liken a @Directive to an Angular 1.0 directive with the option <code>restrict: 'A'</code> (Directives aren't limited to attribute usage.) Directives add behaviour to an existing DOM element or an existing component instance. One example use case for a directive would be to log a click on an element.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> {Directive} <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;

@Directive({
    <span class="hljs-attr">selector</span>: <span class="hljs-string">"[logOnClick]"</span>,
    <span class="hljs-attr">hostListeners</span>: {
        <span class="hljs-string">'click'</span>: <span class="hljs-string">'onClick()'</span>,
    },
})

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">LogOnClick</span> </span>{
    <span class="hljs-keyword">constructor</span>() {}
    onClick() { <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Element clicked!'</span>); }
}
</code></pre>
<p>Which would be used like so:</p>
<pre><code class="lang-js">&lt;button logOnClick&gt;I log when clicked!&lt;;/button&gt;
</code></pre>
<h3 id="heading-components">Components</h3>
<p>A component, rather than adding/modifying behaviour, actually creates its own view (hierarchy of DOM elements) with attached behaviour. An example use case for this might be a contact card component:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> {Component, View} <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;

@Component({
  <span class="hljs-attr">selector</span>: <span class="hljs-string">'contact-card'</span>,
  <span class="hljs-attr">template</span>: <span class="hljs-string">`
    &lt;div&gt;
      &lt;h1&gt;{{name}}&lt;/h1&gt;
      &lt;p&gt;{{city}}&lt;/p&gt;
    &lt;/div&gt;
  `</span>
})
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ContactCard</span> </span>{
  @Input() name: string
  @Input() city: string
  <span class="hljs-keyword">constructor</span>() {}
}
</code></pre>
<p>Which would be used like so:</p>
<pre><code class="lang-js">&lt;contact-card [name]=<span class="hljs-string">"'foo'"</span> [city]=<span class="hljs-string">"'bar'"</span>&gt;&lt;/contact-card&gt;
</code></pre>
<p><code>ContactCard</code> is a reusable UI component that we could use anywhere in our application, even within other components. These basically make up the UI building blocks of our applications.</p>
<h3 id="heading-in-summary">In summary</h3>
<p>Write a component when you want to create a reusable set of DOM elements of UI with custom behaviour. Write a directive when you want to write reusable behaviour to supplement existing DOM elements.</p>
<p>Sources:</p>
<ul>
<li><a target="_blank" href="https://angular.io/api/core/Directive">@Directive documentation</a></li>
<li><a target="_blank" href="https://angular.io/api/core/Component">@Component documentation</a></li>
<li><a target="_blank" href="http://blog.codeleak.pl/2015/06/angular2hello-world.html">Helpful blog post</a></li>
</ul>
<p><a target="_blank" href="https://stackoverflow.com/questions/32680244"><strong>Source</strong></a><br><strong><a class="post-section-overview" href="#599b">Top</a></strong></p>
<h3 id="heading-angular-http-get-with-typescript-error-httpgetmap-is-not-a-function-in-null">Angular HTTP GET with TypeScript error http.get(…).map is not a function in [null]</h3>
<blockquote>
<p>233+ points _? 1<em>41,917+ viewed   
</em><a target="_blank" href="https://stackoverflow.com/users/4834129/claudiu"><strong>Claudiu</strong></a> <strong>asked,</strong>_</p>
</blockquote>
<p>I have a problem with HTTP in Angular.</p>
<p>I just want to <code>GET</code> a <code>JSON</code> list and show it in the view.</p>
<h4 id="heading-service-class">Service class</h4>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> {Injectable} <span class="hljs-keyword">from</span> <span class="hljs-string">"angular2/core"</span>;
<span class="hljs-keyword">import</span> {Hall} <span class="hljs-keyword">from</span> <span class="hljs-string">"./hall"</span>;
<span class="hljs-keyword">import</span> {Http} <span class="hljs-keyword">from</span> <span class="hljs-string">"angular2/http"</span>;
@Injectable()
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">HallService</span> </span>{
    public http:Http;
    public <span class="hljs-keyword">static</span> PATH:string = <span class="hljs-string">'app/backend/'</span> 

    <span class="hljs-keyword">constructor</span>(http:Http) {
        <span class="hljs-built_in">this</span>.http=http;
    }

    getHalls() {
           <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.http.get(HallService.PATH + <span class="hljs-string">'hall.json'</span>).map(<span class="hljs-function">(<span class="hljs-params">res:Response</span>) =&gt;</span> res.json());
    }
}
</code></pre>
<p>And in the <code>HallListComponent</code> I call the <code>getHalls</code> method from the service:</p>
<pre><code class="lang-js"><span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">HallListComponent</span> <span class="hljs-title">implements</span> <span class="hljs-title">OnInit</span> </span>{
    public halls:Hall[];
    public _selectedId:number;

    <span class="hljs-keyword">constructor</span>(private _router:Router,
                private _routeParams:RouteParams,
                private _service:HallService) {
        <span class="hljs-built_in">this</span>._selectedId = +_routeParams.get(<span class="hljs-string">'id'</span>);
    }

    ngOnInit() {
        <span class="hljs-built_in">this</span>._service.getHalls().subscribe(<span class="hljs-function">(<span class="hljs-params">halls:Hall[]</span>)=&gt;</span>{ 
            <span class="hljs-built_in">this</span>.halls=halls;
        });
    }
}
</code></pre>
<p>However, I got an exception:</p>
<p><code>TypeError: this.http.get(...).map is not a function in [null]</code></p>
<h4 id="heading-hall-centercomponent">hall-center.component</h4>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> {Component} <span class="hljs-keyword">from</span> <span class="hljs-string">"angular2/core"</span>;
<span class="hljs-keyword">import</span> {RouterOutlet} <span class="hljs-keyword">from</span> <span class="hljs-string">"angular2/router"</span>;
<span class="hljs-keyword">import</span> {HallService} <span class="hljs-keyword">from</span> <span class="hljs-string">"./hall.service"</span>;
<span class="hljs-keyword">import</span> {RouteConfig} <span class="hljs-keyword">from</span> <span class="hljs-string">"angular2/router"</span>;
<span class="hljs-keyword">import</span> {HallListComponent} <span class="hljs-keyword">from</span> <span class="hljs-string">"./hall-list.component"</span>;
<span class="hljs-keyword">import</span> {HallDetailComponent} <span class="hljs-keyword">from</span> <span class="hljs-string">"./hall-detail.component"</span>;
@Component({
    <span class="hljs-attr">template</span>:<span class="hljs-string">`
        &lt;h2&gt;my app&lt;/h2&gt;
        &lt;router-outlet&gt;&lt;/router-outlet&gt;
    `</span>,
    <span class="hljs-attr">directives</span>: [RouterOutlet],
    <span class="hljs-attr">providers</span>: [HallService]
})

@RouteConfig([
    {<span class="hljs-attr">path</span>: <span class="hljs-string">'/'</span>,         <span class="hljs-attr">name</span>: <span class="hljs-string">'HallCenter'</span>, <span class="hljs-attr">component</span>:HallListComponent, <span class="hljs-attr">useAsDefault</span>:<span class="hljs-literal">true</span>},
    {<span class="hljs-attr">path</span>: <span class="hljs-string">'/hall-list'</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'HallList'</span>, <span class="hljs-attr">component</span>:HallListComponent}
])

<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">HallCenterComponent</span></span>{}
</code></pre>
<h4 id="heading-appcomponent">app.component</h4>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> {Component} <span class="hljs-keyword">from</span> <span class="hljs-string">'angular2/core'</span>;
<span class="hljs-keyword">import</span> {ROUTER_DIRECTIVES} <span class="hljs-keyword">from</span> <span class="hljs-string">"angular2/router"</span>;
<span class="hljs-keyword">import</span> {RouteConfig} <span class="hljs-keyword">from</span> <span class="hljs-string">"angular2/router"</span>;
<span class="hljs-keyword">import</span> {HallCenterComponent} <span class="hljs-keyword">from</span> <span class="hljs-string">"./hall/hall-center.component"</span>;
@Component({
    <span class="hljs-attr">selector</span>: <span class="hljs-string">'my-app'</span>,
    <span class="hljs-attr">template</span>: <span class="hljs-string">`
        &lt;h1&gt;Examenopdracht Factory&lt;/h1&gt;
        &lt;a [routerLink]="['HallCenter']"&gt;Hall overview&lt;/a&gt;
        &lt;router-outlet&gt;&lt;/router-outlet&gt;
    `</span>,
    <span class="hljs-attr">directives</span>: [ROUTER_DIRECTIVES]
})

@RouteConfig([
    {<span class="hljs-attr">path</span>: <span class="hljs-string">'/hall-center/...'</span>, <span class="hljs-attr">name</span>:<span class="hljs-string">'HallCenter'</span>,<span class="hljs-attr">component</span>:HallCenterComponent,<span class="hljs-attr">useAsDefault</span>:<span class="hljs-literal">true</span>}
])
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AppComponent</span> </span>{ }
</code></pre>
<h4 id="heading-tsconfigjson">tsconfig.json</h4>
<pre><code class="lang-json">{
  <span class="hljs-attr">"compilerOptions"</span>: {
    <span class="hljs-attr">"target"</span>: <span class="hljs-string">"ES5"</span>,
    <span class="hljs-attr">"module"</span>: <span class="hljs-string">"system"</span>,
    <span class="hljs-attr">"moduleResolution"</span>: <span class="hljs-string">"node"</span>,
    <span class="hljs-attr">"sourceMap"</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">"emitDecoratorMetadata"</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">"experimentalDecorators"</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">"removeComments"</span>: <span class="hljs-literal">false</span>,
    <span class="hljs-attr">"noImplicitAny"</span>: <span class="hljs-literal">false</span>
  },
  <span class="hljs-attr">"exclude"</span>: [
    <span class="hljs-string">"node_modules"</span>
  ]
}
</code></pre>
<blockquote>
<p><a target="_blank" href="https://stackoverflow.com/users/1873365"><strong><em>Thierry Templier</em></strong></a> <strong><em>answered, (416+ points)</em></strong></p>
</blockquote>
<p>I think that you need to import this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> <span class="hljs-string">'rxjs/add/operator/map'</span>
</code></pre>
<p>Or more generally this if you want to have more methods for observables. <strong>WARNING: This will import all 50+ operators and add them to your application, thus affecting your bundle size and load times.</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> <span class="hljs-string">'rxjs/Rx'</span>;
</code></pre>
<p>See <a target="_blank" href="https://github.com/angular/angular/issues/5632#issuecomment-167026172">this issue</a> for more details.</p>
<p><a target="_blank" href="https://stackoverflow.com/questions/34515173"><strong>Source</strong></a><br><strong><a class="post-section-overview" href="#599b">Top</a></strong></p>
<h3 id="heading-how-to-use-jquery-with-angular">How to use jQuery with Angular?</h3>
<blockquote>
<p>233+ points _? 2<em>46,869+ viewed   
</em><strong><a target="_blank" href="https://stackoverflow.com/users/2398523/waog">Waog</a> asked,</strong>_</p>
</blockquote>
<p>Can anyone tell me, how to use <strong>jQuery</strong> with <strong>Angular</strong>?</p>
<pre><code class="lang-js"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyComponent</span> </span>{
    <span class="hljs-keyword">constructor</span>() {
        <span class="hljs-comment">// how to query the DOM element from here?</span>
    }
}
</code></pre>
<p>I’m aware there are workarounds like manipulating the <em>class</em> or <em>id</em> of the DOM element upfront, but I’m hoping for a cleaner way of doing it.</p>
<blockquote>
<p><a target="_blank" href="https://stackoverflow.com/users/2881743"><strong><em>werenskjold</em></strong></a> <strong><em>answered, (258+ points)</em></strong></p>
</blockquote>
<p>Using jQuery from Angular2 is a breeze compared to ng1. If you are using TypeScript you could first reference jQuery typescript definition.</p>
<pre><code class="lang-bash">tsd install jquery --save
or
typings install dt~jquery --global --save
</code></pre>
<p>TypescriptDefinitions are not required since you could just use <code>any</code> as the type for <code>$</code> or <code>jQuery</code></p>
<p>In your angular component you should reference a DOM element from the template using <code>@ViewChild()</code> After the view has been initialized you can use the <code>nativeElement</code> property of this object and pass to jQuery.</p>
<p>Declaring <code>$</code> (or <code>jQuery</code>) as JQueryStatic will give you a typed reference to jQuery.</p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> {bootstrap}    <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/platform-browser-dynamic'</span>;
<span class="hljs-keyword">import</span> {Component, ViewChild, ElementRef, AfterViewInit} <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;
<span class="hljs-keyword">declare</span> <span class="hljs-keyword">var</span> $:JQueryStatic;

<span class="hljs-meta">@Component</span>({
    selector: <span class="hljs-string">'ng-chosen'</span>,
    template: <span class="hljs-string">`&lt;select #selectElem&gt;
        &lt;option *ngFor="#item of items" [value]="item" [selected]="item === selectedValue"&gt;{{item}} option&lt;/option&gt;
        &lt;/select&gt;
        &lt;h4&gt; {{selectedValue}}&lt;/h4&gt;`</span>
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> NgChosenComponent <span class="hljs-keyword">implements</span> AfterViewInit {
    <span class="hljs-meta">@ViewChild</span>(<span class="hljs-string">'selectElem'</span>) el:ElementRef;
    items = [<span class="hljs-string">'First'</span>, <span class="hljs-string">'Second'</span>, <span class="hljs-string">'Third'</span>];
    selectedValue = <span class="hljs-string">'Second'</span>;

    ngAfterViewInit() {
        $(<span class="hljs-built_in">this</span>.el.nativeElement)
            .chosen()
            .on(<span class="hljs-string">'change'</span>, <span class="hljs-function">(<span class="hljs-params">e, args</span>) =&gt;</span> {
                <span class="hljs-built_in">this</span>.selectedValue = args.selected;
            });
    }
}

bootstrap(NgChosenComponent);
</code></pre>
<p>This example is available on plunker: <a target="_blank" href="http://plnkr.co/edit/Nq9LnK?p=preview">http://plnkr.co/edit/Nq9LnK?p=preview</a></p>
<p>tslint will complain about <code>chosen</code> not being a property on $, to fix this you can add a definition to the JQuery interface in your custom *.d.ts file</p>
<pre><code class="lang-js">interface JQuery {
    chosen(options?:any):JQuery;
}
</code></pre>
<p><a target="_blank" href="https://stackoverflow.com/questions/30623825"><strong>Source</strong></a><br><strong><a class="post-section-overview" href="#599b">Top</a></strong></p>
<h3 id="heading-angular-exception-no-provider-for-http">Angular EXCEPTION: No provider for Http</h3>
<blockquote>
<p>230+ points _? 1<em>42,976+ viewed   
</em><strong><a target="_blank" href="https://stackoverflow.com/users/516389/daniel">daniel</a> asked,</strong>_</p>
</blockquote>
<p>I am getting the <code>EXCEPTION: No provider for Http!</code> in my Angular app. What am I doing wrong?</p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> {Http, Headers} <span class="hljs-keyword">from</span> <span class="hljs-string">'angular2/http'</span>;
<span class="hljs-keyword">import</span> {Injectable} <span class="hljs-keyword">from</span> <span class="hljs-string">'angular2/core'</span>

<span class="hljs-meta">@Component</span>({
    selector: <span class="hljs-string">'greetings-ac-app2'</span>,
    providers: [],
    templateUrl: <span class="hljs-string">'app/greetings-ac2.html'</span>,
    directives: [NgFor, NgModel, NgIf, FORM_DIRECTIVES],
    pipes: []
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> GreetingsAcApp2 {
    <span class="hljs-keyword">private</span> str:<span class="hljs-built_in">any</span>;

    <span class="hljs-keyword">constructor</span>(<span class="hljs-params">http: Http</span>) {

        <span class="hljs-built_in">this</span>.str = {str:<span class="hljs-string">'test'</span>};
        http.post(<span class="hljs-string">'http://localhost:18937/account/registeruiduser/'</span>,
            <span class="hljs-built_in">JSON</span>.stringify(<span class="hljs-built_in">this</span>.str),
            {
                headers: <span class="hljs-keyword">new</span> Headers({
                    <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>
                })
            });
</code></pre>
<blockquote>
<p><a target="_blank" href="https://stackoverflow.com/users/2083492"><strong><em>Philip Miglinci</em></strong></a> <strong><em>answered, (381+ points)</em></strong></p>
</blockquote>
<p>Import the HttpModule</p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> { HttpModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/http'</span>;

<span class="hljs-meta">@NgModule</span>({
    imports: [ BrowserModule, HttpModule ],
    providers: [],
    declarations: [ AppComponent ],
    bootstrap: [ AppComponent ]
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">class</span> AppModule { }

platformBrowserDynamic().bootstrapModule(AppModule);
</code></pre>
<p>Ideally you split up this code in two separate files. For further information read:</p>
<ul>
<li><a target="_blank" href="https://angular.io/docs/ts/latest/cookbook/rc4-to-rc5.html">https://angular.io/docs/ts/latest/cookbook/rc4-to-rc5.html</a></li>
<li><a target="_blank" href="https://angular.io/docs/ts/latest/guide/ngmodule.html">https://angular.io/docs/ts/latest/guide/ngmodule.html</a></li>
</ul>
<p><a target="_blank" href="https://stackoverflow.com/questions/33721276"><strong>Source</strong></a><br><strong><a class="post-section-overview" href="#599b">Top</a></strong></p>
<h3 id="heading-cant-bind-to-formgroup-since-it-isnt-a-known-property-of-form">Can’t bind to ‘formGroup’ since it isn’t a known property of ‘form’</h3>
<blockquote>
<p>227+ points _? 1<em>27,130+ viewed   
</em><strong><a target="_blank" href="https://stackoverflow.com/users/2433664/francescomussi">johnnyfittizio</a> asked,</strong>_</p>
</blockquote>
<p><strong>THE SITUATION:</strong></p>
<p>Please help! I am trying to make what should be a very simple form in my Angular2 app but no matter what it never works.</p>
<p><strong>ANGULAR VERSION:</strong></p>
<p>Angular 2.0.0 Rc5</p>
<p><strong>THE ERROR:</strong></p>
<pre><code>Can<span class="hljs-string">'t bind to '</span>formGroup<span class="hljs-string">' since it isn'</span>t a known property <span class="hljs-keyword">of</span> <span class="hljs-string">'form'</span>
</code></pre><p><img src="https://cdn-media-1.freecodecamp.org/images/SP8f73A8L3lPs6fS9frNubiN5UEniPY2yj3p" alt="Image" width="800" height="248" loading="lazy"></p>
<p><strong>THE CODE:</strong></p>
<p>The view:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> [<span class="hljs-attr">formGroup</span>]=<span class="hljs-string">"newTaskForm"</span> (<span class="hljs-attr">submit</span>)=<span class="hljs-string">"createNewTask()"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"form-group"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"name"</span>&gt;</span>Name<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"name"</span> <span class="hljs-attr">required</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
     <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"btn btn-default"</span>&gt;</span>Submit<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></pre>
<p>The controller:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> { Component } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;
<span class="hljs-keyword">import</span> { FormGroup, FormControl, Validators, FormBuilder }  <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/forms'</span>;
<span class="hljs-keyword">import</span> {FormsModule,ReactiveFormsModule} <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/forms'</span>;
<span class="hljs-keyword">import</span> { Task } <span class="hljs-keyword">from</span> <span class="hljs-string">'./task'</span>;

<span class="hljs-meta">@Component</span>({
    selector: <span class="hljs-string">'task-add'</span>,
    templateUrl: <span class="hljs-string">'app/task-add.component.html'</span>

})

<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> TaskAddComponent {

    newTaskForm: FormGroup;

    <span class="hljs-keyword">constructor</span>(<span class="hljs-params">fb: FormBuilder</span>) 
    {
        <span class="hljs-built_in">this</span>.newTaskForm = fb.group({
            name: [<span class="hljs-string">""</span>, Validators.required]
        });
    }

    createNewTask()
    {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.newTaskForm.value)
    }

}
</code></pre>
<p>The ngModule:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> { NgModule }      <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;
<span class="hljs-keyword">import</span> { BrowserModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/platform-browser'</span>;
<span class="hljs-keyword">import</span> { FormsModule }   <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/forms'</span>;

<span class="hljs-keyword">import</span> { routing }        <span class="hljs-keyword">from</span> <span class="hljs-string">'./app.routing'</span>;
<span class="hljs-keyword">import</span> { AppComponent }  <span class="hljs-keyword">from</span> <span class="hljs-string">'./app.component'</span>;
<span class="hljs-keyword">import</span> { TaskService } <span class="hljs-keyword">from</span> <span class="hljs-string">'./task.service'</span>

<span class="hljs-meta">@NgModule</span>({
    imports: [ 
        BrowserModule,
        routing,
        FormsModule
    ],
    declarations: [ AppComponent ],
    providers: [
        TaskService
    ],
    bootstrap: [ AppComponent ]
})

<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> AppModule { }
</code></pre>
<p><strong>THE QUESTION:</strong></p>
<p>Why am I getting that error?</p>
<p>Am I missing something?</p>
<blockquote>
<p><a target="_blank" href="https://stackoverflow.com/users/6677986"><strong><em>Stefan Svrkota</em></strong></a> <strong><em>answered, (465+ points)</em></strong></p>
</blockquote>
<p><strong>RC5 FIX</strong></p>
<p>You need to <code>import { REACTIVE_FORM_DIRECTIVES } from '@angular/forms'</code> in your controller and add it to <code>directives</code> in <code>@Component</code>. That will fix the problem.</p>
<p>After you fix that, you will probably get another error because you didn’t add <code>formControlName="name"</code> to your input in form.</p>
<p><strong>RC6/RC7/Final release FIX</strong></p>
<p>To fix this error, you just need to import <code>ReactiveFormsModule</code> from <code>@angular/forms</code> in your module. Here's the example of a basic module with <code>ReactiveFormsModule</code> import:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> { NgModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;
<span class="hljs-keyword">import</span> { BrowserModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/platform-browser'</span>;
<span class="hljs-keyword">import</span> { FormsModule, ReactiveFormsModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/forms'</span>;
<span class="hljs-keyword">import</span> { AppComponent }  <span class="hljs-keyword">from</span> <span class="hljs-string">'./app.component'</span>;

<span class="hljs-meta">@NgModule</span>({
    imports: [
        BrowserModule,
        FormsModule,
        ReactiveFormsModule
    ],
    declarations: [
        AppComponent
    ],
    bootstrap: [AppComponent]
})

<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> AppModule { }
</code></pre>
<p>To explain further, <code>formGroup</code> is a selector for directive named <code>FormGroupDirective</code> that is a part of <code>ReactiveFormsModule</code>, hence the need to import it. It is used to bind an existing <code>FormGroup</code> to a DOM element. You can read more about it on <a target="_blank" href="https://angular.io/docs/ts/latest/api/forms/index/FormGroupDirective-directive.html">Angular's official docs page</a>.</p>
<p><a target="_blank" href="https://stackoverflow.com/questions/39152071"><strong>Source</strong></a><br><strong><a class="post-section-overview" href="#599b">Top</a></strong></p>
<h3 id="heading-angular-di-error-exception-cant-resolve-all-parameters">Angular DI Error — EXCEPTION: Can’t resolve all parameters</h3>
<blockquote>
<p>221+ points _? 1<em>42,497+ viewed   
</em><strong><a target="_blank" href="https://stackoverflow.com/users/4321757/keith-otto">Keith Otto</a> asked,</strong>_</p>
</blockquote>
<p>I’ve built a basic app in Angular, but I have encountered a strange issue where I cannot inject a service into one of my components. It injects fine into any of the three other components I have created however.</p>
<p>For starters, this is the service:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> { Injectable } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;

<span class="hljs-meta">@Injectable</span>()
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> MobileService {
  screenWidth: <span class="hljs-built_in">number</span>;
  screenHeight: <span class="hljs-built_in">number</span>;

  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"></span>) {
    <span class="hljs-built_in">this</span>.screenWidth = <span class="hljs-built_in">window</span>.outerWidth;
    <span class="hljs-built_in">this</span>.screenHeight = <span class="hljs-built_in">window</span>.outerHeight;

    <span class="hljs-built_in">window</span>.addEventListener(<span class="hljs-string">"resize"</span>, <span class="hljs-built_in">this</span>.onWindowResize.bind(<span class="hljs-built_in">this</span>) )
  }

  onWindowResize(ev: Event) {
    <span class="hljs-keyword">var</span> win = (ev.currentTarget <span class="hljs-keyword">as</span> Window);
    <span class="hljs-built_in">this</span>.screenWidth = win.outerWidth;
    <span class="hljs-built_in">this</span>.screenHeight = win.outerHeight;
  }

}
</code></pre>
<p>And the component that it refuses to work with:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> { Component, } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;
<span class="hljs-keyword">import</span> { NgClass } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/common'</span>;
<span class="hljs-keyword">import</span> { ROUTER_DIRECTIVES } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/router'</span>;

<span class="hljs-keyword">import</span> {MobileService} <span class="hljs-keyword">from</span> <span class="hljs-string">'../'</span>;

<span class="hljs-meta">@Component</span>({
  moduleId: <span class="hljs-built_in">module</span>.id,
  selector: <span class="hljs-string">'pm-header'</span>,
  templateUrl: <span class="hljs-string">'header.component.html'</span>,
  styleUrls: [<span class="hljs-string">'header.component.css'</span>],
  directives: [ROUTER_DIRECTIVES, NgClass],
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> HeaderComponent {
  mobileNav: <span class="hljs-built_in">boolean</span> = <span class="hljs-literal">false</span>;

  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">public</span> ms: MobileService</span>) {
    <span class="hljs-built_in">console</span>.log(ms);
  }

}
</code></pre>
<p>The error I get in the browser console is this:</p>
<p><code>EXCEPTION: Can't resolve all parameters for HeaderComponent: (?).</code></p>
<p>I have the service in the bootstrap function so it has a provider. And I seem to be able to inject it into the constructor of any of my other components without issue.</p>
<blockquote>
<p><a target="_blank" href="https://stackoverflow.com/users/217408"><strong><em>Günter Zöchbauer</em></strong></a> <strong><em>answered, (272+ points)</em></strong></p>
</blockquote>
<p>Import it from the file where it is declared directly instead of the barrel.</p>
<p>I don’t know what exactly causes the issue but I saw it mentioned several times (probably some kind of circular dependency).</p>
<p>It should also be fixable by changing the order of the exports in the barrel (don’t know details, but was mentioned as well)</p>
<p><a target="_blank" href="https://stackoverflow.com/questions/37997824"><strong>Source</strong></a><br><strong><a class="post-section-overview" href="#599b">Top</a></strong></p>
<h3 id="heading-angular-set-headers-for-every-request">Angular — Set headers for every request</h3>
<blockquote>
<p>209+ points _? 2<em>05,557+ viewed   
</em><strong><a target="_blank" href="https://stackoverflow.com/users/4135178/avijit-gupta">Avijit Gupta</a> asked,</strong>_</p>
</blockquote>
<p>I need to set some Authorization headers after the user has logged in, for every subsequent request.</p>
<p>To set headers for a particular request,</p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> {Headers} <span class="hljs-keyword">from</span> <span class="hljs-string">'angular2/http'</span>;
<span class="hljs-keyword">var</span> headers = <span class="hljs-keyword">new</span> Headers();
headers.append(headerName, value);

<span class="hljs-comment">// HTTP POST using these headers</span>
<span class="hljs-built_in">this</span>.http.post(url, data, {
  headers: headers
})
<span class="hljs-comment">// do something with the response</span>
</code></pre>
<p><a target="_blank" href="https://auth0.com/blog/2015/10/15/angular-2-series-part-3-using-http/">Reference</a></p>
<p>But it would be not be feasible to manually set request headers for every request in this way.</p>
<p>How do I set the headers set once the user has logged in, and also remove those headers on logout?</p>
<blockquote>
<p><a target="_blank" href="https://stackoverflow.com/users/1873365"><strong><em>Thierry Templier</em></strong></a> <strong><em>answered, (283+ points)</em></strong></p>
</blockquote>
<p>To answer, you question you could provide a service that wraps the original <code>Http</code> object from Angular. Something like described below.</p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> {Injectable} <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;
<span class="hljs-keyword">import</span> {Http, Headers} <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/http'</span>;

<span class="hljs-meta">@Injectable</span>()
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> HttpClient {

  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> http: Http</span>) {}

  createAuthorizationHeader(headers: Headers) {
    headers.append(<span class="hljs-string">'Authorization'</span>, <span class="hljs-string">'Basic '</span> +
      btoa(<span class="hljs-string">'username:password'</span>)); 
  }

  get(url) {
    <span class="hljs-keyword">let</span> headers = <span class="hljs-keyword">new</span> Headers();
    <span class="hljs-built_in">this</span>.createAuthorizationHeader(headers);
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.http.get(url, {
      headers: headers
    });
  }

  post(url, data) {
    <span class="hljs-keyword">let</span> headers = <span class="hljs-keyword">new</span> Headers();
    <span class="hljs-built_in">this</span>.createAuthorizationHeader(headers);
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.http.post(url, data, {
      headers: headers
    });
  }
}
</code></pre>
<p>And instead of injecting the <code>Http</code> object you could inject this one (<code>HttpClient</code>).</p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> { HttpClient } <span class="hljs-keyword">from</span> <span class="hljs-string">'./http-client'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> MyComponent {
  <span class="hljs-comment">// Notice we inject "our" HttpClient here, naming it Http so it's easier</span>
  <span class="hljs-keyword">constructor</span>(<span class="hljs-params">http: HttpClient</span>) {
    <span class="hljs-built_in">this</span>.http = httpClient;
  }

  handleSomething() {
    <span class="hljs-built_in">this</span>.http.post(url, data).subscribe(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> {
        <span class="hljs-comment">// console.log( result );</span>
    });
  }
}
</code></pre>
<p>I also think that something could be done using multi providers for the <code>Http</code> class by providing your own class extending the <code>Http</code> one... See this link: <a target="_blank" href="http://blog.thoughtram.io/angular2/2015/11/23/multi-providers-in-angular-2.html">http://blog.thoughtram.io/angular2/2015/11/23/multi-providers-in-angular-2.html</a>.</p>
<p><a target="_blank" href="https://stackoverflow.com/questions/34464108"><strong>Source</strong></a><br><strong><a class="post-section-overview" href="#599b">Top</a></strong></p>
<h3 id="heading-how-to-use-ngif-else-in-angular">How to use *ngIf else in Angular?</h3>
<blockquote>
<p>205+ points _? 2<em>03,768+ viewed   
</em><a target="_blank" href="https://stackoverflow.com/users/5486494/kawli-norman"><strong>kawli norman</strong></a> <strong>asked,</strong>_</p>
</blockquote>
<p>I’m using Angular and I want to use <code>*ngIf else</code> (available since version 4) in this example:</p>
<pre><code>&lt;div *ngIf=<span class="hljs-string">"isValid"</span>&gt;
  content here ...
&lt;/div&gt;

<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> *<span class="hljs-attr">ngIf</span>=<span class="hljs-string">"!isValid"</span>&gt;</span>
 other content here...
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
</code></pre><p>How can I acheive the same behavior with <code>ngIf else</code> ?</p>
<blockquote>
<p><a target="_blank" href="https://stackoverflow.com/users/7273246"><strong><em>Bougarfaoui El houcine</em></strong></a> <strong><em>answered, (384+ points)</em></strong></p>
</blockquote>
<p><strong>Angular 4 and 5</strong>:</p>
<p>using <code>else</code> :</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> *<span class="hljs-attr">ngIf</span>=<span class="hljs-string">"isValid;else other_content"</span>&gt;</span>
    content here ...
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">ng-template</span> #<span class="hljs-attr">other_content</span>&gt;</span>other content here...<span class="hljs-tag">&lt;/<span class="hljs-name">ng-template</span>&gt;</span>
</code></pre>
<p>you can also use <code>then else</code> :</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> *<span class="hljs-attr">ngIf</span>=<span class="hljs-string">"isValid;then content else other_content"</span>&gt;</span>here is ignored<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">ng-template</span> #<span class="hljs-attr">content</span>&gt;</span>content here...<span class="hljs-tag">&lt;/<span class="hljs-name">ng-template</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">ng-template</span> #<span class="hljs-attr">other_content</span>&gt;</span>other content here...<span class="hljs-tag">&lt;/<span class="hljs-name">ng-template</span>&gt;</span>
</code></pre>
<p>or <code>then</code> alone :</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> *<span class="hljs-attr">ngIf</span>=<span class="hljs-string">"isValid;then content"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">ng-template</span> #<span class="hljs-attr">content</span>&gt;</span>content here...<span class="hljs-tag">&lt;/<span class="hljs-name">ng-template</span>&gt;</span>
</code></pre>
<p><strong>Demo :</strong></p>
<p><a target="_blank" href="https://plnkr.co/edit/XD5vLvmwTApcaHJ66Is1"><strong>Plunker</strong></a></p>
<p><strong>Details:</strong></p>
<p><code>&lt;ng-template&gt;</code> : is Angular’s own implementation of the <code>&lt;template&gt;</code> tag which is <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template">according to MDN</a> :</p>
<p><code>The HTML &lt;template&gt; element is a mechanism for holding client-side content that is not to be rendered when a page is loaded but may subsequently be instantiated during runtime using JavaS</code>cript.</p>
<p><a target="_blank" href="https://stackoverflow.com/questions/43006550"><strong>Source</strong></a><br><strong><a class="post-section-overview" href="#599b">Top</a></strong></p>
<h3 id="heading-angular-no-provider-for-nameservice">Angular no provider for NameService</h3>
<blockquote>
<p>196+ points _? 1<em>86,526+ viewed   
</em><strong><a target="_blank" href="https://stackoverflow.com/users/2667885/m-svrcek">M.Svrcek</a> asked,</strong>_</p>
</blockquote>
<p>I’ve got problem with loading class into Angular component. I’m trying to solve for long time, even tried to add it to single file. What I have is:</p>
<p><strong>Application.ts</strong></p>
<pre><code class="lang-ts"><span class="hljs-comment">/// &lt;reference path="../typings/angular2/angular2.d.ts" /&gt;</span>

<span class="hljs-keyword">import</span> {Component,View,bootstrap,NgFor} <span class="hljs-keyword">from</span> <span class="hljs-string">"angular2/angular2"</span>;
<span class="hljs-keyword">import</span> {NameService} <span class="hljs-keyword">from</span> <span class="hljs-string">"./services/NameService"</span>;

<span class="hljs-meta">@Component</span>({
    selector:<span class="hljs-string">'my-app'</span>,
    injectables: [NameService]
})
<span class="hljs-meta">@View</span>({
    template:<span class="hljs-string">'&lt;h1&gt;Hi {{name}}&lt;/h1&gt;'</span> +
    <span class="hljs-string">'&lt;p&gt;Friends&lt;/p&gt;'</span> +
    <span class="hljs-string">'&lt;ul&gt;'</span> +
    <span class="hljs-string">'   &lt;li *ng-for="#name of names"&gt;{{name}}&lt;/li&gt;'</span> +
    <span class="hljs-string">'&lt;/ul&gt;'</span>,
    directives:[NgFor]
})

<span class="hljs-keyword">class</span> MyAppComponent
{
    name:<span class="hljs-built_in">string</span>;
    names:<span class="hljs-built_in">Array</span>&lt;<span class="hljs-built_in">string</span>&gt;;

    <span class="hljs-keyword">constructor</span>(<span class="hljs-params">nameService:NameService</span>)
    {
        <span class="hljs-built_in">this</span>.name = <span class="hljs-string">'Michal'</span>;
        <span class="hljs-built_in">this</span>.names = nameService.getNames();
    }
}
bootstrap(MyAppComponent);
</code></pre>
<p><strong>services/NameService.ts</strong></p>
<pre><code class="lang-ts"><span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> NameService {
    names: <span class="hljs-built_in">Array</span>&lt;<span class="hljs-built_in">string</span>&gt;;
    <span class="hljs-keyword">constructor</span>(<span class="hljs-params"></span>) {
        <span class="hljs-built_in">this</span>.names = [<span class="hljs-string">"Alice"</span>, <span class="hljs-string">"Aarav"</span>, <span class="hljs-string">"Martín"</span>, <span class="hljs-string">"Shannon"</span>, <span class="hljs-string">"Ariana"</span>, <span class="hljs-string">"Kai"</span>];
    }
    getNames()
    {
        <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.names;
    }
}
</code></pre>
<p>All the time I’m getting error message saying “No provider for NameService” …</p>
<p>Can someone help me spot that small issue with my code?</p>
<blockquote>
<p><a target="_blank" href="https://stackoverflow.com/users/46194"><strong><em>Klas Mellbourn</em></strong></a> <strong><em>answered, (309+ points)</em></strong></p>
</blockquote>
<p>You have to use <code>providers</code> instead of <code>injectables</code></p>
<pre><code class="lang-ts"><span class="hljs-meta">@Component</span>({
    selector: <span class="hljs-string">'my-app'</span>,
    providers: [NameService]
})
</code></pre>
<p><a target="_blank" href="https://github.com/Mellbourn/angular2-step-by-step-guide">Complete code sample here</a>.</p>
<p><a target="_blank" href="https://stackoverflow.com/questions/30580083"><strong>Source</strong></a><br><strong><a class="post-section-overview" href="#599b">Top</a></strong></p>
<h3 id="heading-binding-select-element-to-object-in-angular">Binding select element to object in Angular</h3>
<blockquote>
<p>194+ points _? 1<em>97,048+ viewed   
</em><a target="_blank" href="https://stackoverflow.com/users/372296/rharris"><strong>RHarris</strong></a> <strong>asked,</strong>_</p>
</blockquote>
<p>I’m new to Angular and trying to get up to speed with the new way of doing things.</p>
<p>I’d like to bind a select element to a list of objects — which is easy enough:</p>
<pre><code class="lang-ts"><span class="hljs-meta">@Component</span>({
   selector: <span class="hljs-string">'myApp'</span>,
   template: <span class="hljs-string">`&lt;h1&gt;My Application&lt;/h1&gt;
              &lt;select [(ngModel)]="selectedValue"&gt;
                 &lt;option *ngFor="#c of countries" value="c.id"&gt;{{c.name}}&lt;/option&gt;
              &lt;/select&gt;`</span>
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> AppComponent{
    countries = [
       {id: <span class="hljs-number">1</span>, name: <span class="hljs-string">"United States"</span>},
       {id: <span class="hljs-number">2</span>, name: <span class="hljs-string">"Australia"</span>}
       {id: <span class="hljs-number">3</span>, name: <span class="hljs-string">"Canada"</span>}
       {id: <span class="hljs-number">4</span>, name: <span class="hljs-string">"Brazil"</span>}
       {id: <span class="hljs-number">5</span>, name: <span class="hljs-string">"England"</span>}
     ];
    selectedValue = <span class="hljs-literal">null</span>;
}
</code></pre>
<p>In this case, it appears that selectedValue would be a number — the id of the selected item.</p>
<p>However, I’d actually like to bind to the country object itself so that selectedValue is the object rather than just the id. I tried changing the value of the option like so:</p>
<pre><code class="lang-ts">&lt;option *ngFor=<span class="hljs-string">"#c of countries"</span> value=<span class="hljs-string">"c"</span>&gt;{{c.name}}&lt;;/option&gt;
</code></pre>
<p>but this does not seem to work. It seems to place an object in my selectedValue — but not the object that I’m expecting. You can <a target="_blank" href="http://plnkr.co/edit/HGRGv33EFwxDsSnELofk?p=preview">see this in my Plunker example</a>.</p>
<p>I also tried binding to the change event so that I could set the object myself based on the selected id; however, it appears that the change event fires before the bound ngModel is updated — meaning I don’t have access to the newly selected value at that point.</p>
<p>Is there a clean way to bind a select element to an object with Angular 2?</p>
<blockquote>
<p><a target="_blank" href="https://stackoverflow.com/users/217408"><strong><em>Günter Zöchbauer</em></strong></a> <strong><em>answered, (361+ points)</em></strong></p>
</blockquote>
<pre><code class="lang-ts">&lt;h1&gt;My Application&lt;/h1&gt;
&lt;select [(ngModel)]=<span class="hljs-string">"selectedValue"</span>&gt;
  &lt;option *ngFor=<span class="hljs-string">"let c of countries"</span> [ngValue]=<span class="hljs-string">"c"</span>&gt;{{c.name}}&lt;/option&gt;
&lt;/select&gt;
</code></pre>
<p><a target="_blank" href="https://plnkr.co/edit/njGlIV?p=preview"><strong>Plunker example</strong></a></p>
<p>NOTE: you can use <code>[ngValue]="c"</code> instead of <code>[ngValue]="c.id"</code> where c is the complete country object.</p>
<p><code>[value]="..."</code> only supports string values<br><code>[ngValue]="..."</code> supports any type</p>
<p><strong>update</strong></p>
<p>If the <code>value</code> is an object, the preselected instance needs to be identical with one of the values.</p>
<p>See also the recently added custom comparison <a target="_blank" href="https://github.com/angular/angular/issues/13268">https://github.com/angular/angular/issues/13268</a> <strong>available since 4.0.0-beta.7</strong></p>
<pre><code class="lang-ts">&lt;select [compareWith]=<span class="hljs-string">"compareFn"</span> ...
</code></pre>
<p>Take care of if you want to access <code>this</code> within <code>compareFn</code>.</p>
<pre><code class="lang-ts">compareFn = <span class="hljs-built_in">this</span>._compareFn.bind(<span class="hljs-built_in">this</span>);

<span class="hljs-comment">// or </span>
<span class="hljs-comment">// compareFn = (a, b) =&gt; this._compareFn(a, b);</span>

_comareFn((a, b) {
   <span class="hljs-keyword">if</span>(<span class="hljs-built_in">this</span>.x ...) {
     ...
}
</code></pre>
<p><a target="_blank" href="https://stackoverflow.com/questions/35945001"><strong>Source</strong></a><br><strong><a class="post-section-overview" href="#599b">Top</a></strong></p>
<h3 id="heading-what-is-difference-between-declarations-providers-and-import-in-ngmodule">What is difference between declarations, providers and import in NgModule</h3>
<blockquote>
<p>188+ points _? 5<em>5,432+ viewed   
</em><a target="_blank" href="https://stackoverflow.com/users/2822252/ramesh-papaganti"><strong>Ramesh Papaganti</strong></a> <strong>asked,</strong>_</p>
</blockquote>
<p>I am trying to understand Angular (sometimes called Angular2+), then I came across @Module</p>
<ol>
<li>Imports</li>
<li>Declarations</li>
<li>Providers</li>
</ol>
<p>Following <a target="_blank" href="https://angular.io/guide/quickstart">Angularjs-2 quick start</a></p>
<blockquote>
<p><a target="_blank" href="https://stackoverflow.com/users/217408"><strong><em>Günter Zöchbauer</em></strong></a> <strong><em>answered, (277+ points)</em></strong></p>
</blockquote>
<p><strong>Angular Concepts</strong></p>
<ul>
<li><code>imports</code> makes the exported declarations of other modules available in the current module</li>
<li><code>declarations</code> are to make directives (including components and pipes) from the current module available to other directives in the current module. Selectors of directives, components or pipes are only matched against the HTML if they are declared or imported.</li>
<li><code>providers</code> are to make services and values known to DI. They are added to the root scope and they are injected to other services or directives that have them as dependency.</li>
</ul>
<p>A special case for <code>providers</code> are lazy loaded modules that get their own child injector. <code>providers</code> of a lazy loaded module are only provided to this lazy loaded module by default (not the whole application as it is with other modules).</p>
<p>For more details about modules see also <a target="_blank" href="https://angular.io/docs/ts/latest/guide/ngmodule.html">https://angular.io/docs/ts/latest/guide/ngmodule.html</a></p>
<ul>
<li><code>exports</code> makes the components, directives, and pipes available in modules that add this module to <code>imports</code>. <code>exports</code> can also be used to re-export modules such as CommonModule and FormsModule, which is often done in shared modules.</li>
<li><code>entryComponents</code> registers components for offline compilation so that they can be used with <code>ViewContainerRef.createComponent()</code>. Components used in router configurations are added implicitly.</li>
</ul>
<p><strong>TypeScript (ES2015) imports</strong></p>
<p><code>import ... from 'foo/bar'</code> (which <a target="_blank" href="https://stackoverflow.com/a/38158884/1175496">may resolve to an <code>index.ts</code></a>) are for TypeScript imports. You need these whenever you use an identifier in a typescript file that is declared in another typescript file.</p>
<p>Angular’s <code>@NgModule()</code> <code>imports</code> and TypeScript <code>import</code> are <em>entirely different concepts</em>.</p>
<p>See also <a target="_blank" href="https://blog.jdriven.com/2017/06/typescript-and-es6-import-syntax/">jDriven — TypeScript and ES6 import syntax</a></p>
<p><code>Most of them are actually plain ECMAScript 2015 (ES6) module syntax that TypeScript uses as well.</code></p>
<p><a target="_blank" href="https://stackoverflow.com/questions/39062930"><strong>Source</strong></a><br><strong><a class="post-section-overview" href="#599b">Top</a></strong></p>
<h3 id="heading-in-angular-how-do-you-determine-the-active-route">In Angular, how do you determine the active route?</h3>
<blockquote>
<p>187+ points _? 1<em>00,870+ viewed   
</em><a target="_blank" href="https://stackoverflow.com/users/1480995/michael-oryl"><strong>Michael Oryl</strong></a> <strong>asked,</strong>_</p>
</blockquote>
<p><strong>NOTE:</strong> <em>There are many different answers here, and most have been valid at one time or another. The fact is that what works has changed a number of times as the Angular team has changed its Router. The Router 3.0 version that will eventually be <strong>the</strong> router in Angular breaks many of these solutions, but offers a very simple solution of its own. As of RC.3, the preferred solution is to use <code>[routerLinkActive]</code> as shown in <a target="_blank" href="https://stackoverflow.com/a/37947435/1480995">this answer</a>.</em></p>
<p>In an Angular application (current in the 2.0.0-beta.0 release as I write this), how do you determine what the currently active route is?</p>
<p>I’m working on an app that uses Bootstrap 4 and I need a way to mark navigation links/buttons as active when their associated component is being shown in a <code>&lt;router-outp</code>ut&gt; tag.</p>
<p>I realize that I could maintain the state myself when one of the buttons is clicked upon, but that wouldn’t cover the case of having multiple paths into the same route (say a main navigation menu as well as a local menu in the main component).</p>
<p>Any suggestions or links would be appreciated. Thanks.</p>
<blockquote>
<p><a target="_blank" href="https://stackoverflow.com/users/974981"><strong><em>jessepinho</em></strong></a> <strong><em>answered, (229+ points)</em></strong></p>
</blockquote>
<p>With the new <a target="_blank" href="https://github.com/angular/vladivostok">Angular router</a>, you can add a <code>[routerLinkActive]="['your-class-name']"</code> attribute to all your links:</p>
<pre><code>&lt;a [routerLink]=<span class="hljs-string">"['/home']"</span> [routerLinkActive]=<span class="hljs-string">"['is-active']"</span>&gt;Home&lt;/a&gt;
</code></pre><p>Or the simplified non-array format if only one class is needed:</p>
<pre><code>&lt;a [routerLink]=<span class="hljs-string">"['/home']"</span> [routerLinkActive]=<span class="hljs-string">"'is-active'"</span>&gt;Home&lt;/a&gt;
</code></pre><p>See the <a target="_blank" href="https://github.com/angular/angular/blob/ae75e3640a2d9eb1e897a0771d92b976c5a42c75/modules/%40angular/router/src/directives/router_link_active.ts">poorly documented <code>routerLinkActive</code> directive</a> for more info. (I mostly figured this out via trial-and-error.)</p>
<p>UPDATE: Better documentation for the <code>routerLinkActive</code> directive can now be found <a target="_blank" href="https://angular.io/docs/ts/latest/api/router/index/RouterLinkActive-directive.html">here</a>. (Thanks to @Victor Hugo Arango A. in the comments below.)</p>
<p><a target="_blank" href="https://stackoverflow.com/questions/34323480"><strong>Source</strong></a><br><strong><a class="post-section-overview" href="#599b">Top</a></strong></p>
<h3 id="heading-angular-cli-sass-options">Angular CLI SASS options</h3>
<blockquote>
<p>187+ points _? 1<em>06,289+ viewed   
</em><a target="_blank" href="https://stackoverflow.com/users/2109585/jdillon522"><strong>JDillon522</strong></a> <strong>asked,</strong>_</p>
</blockquote>
<p>I’m new to Angular and I’m coming from the Ember community. Trying to use the new Angular-CLI based off of Ember-CLI.</p>
<p>I need to know the best way to handle SASS in a new Angular project. I tried using the <code>[ember-cli-sass](https://github.com/aexmachina/ember-cli-sass)</code> repo to see if it would play along since a number of core components of the Angular-CLI are run off of Ember-CLI modules.</p>
<p>It didnt work but than again not sure if I just misconfigured something.</p>
<p>Also, what is the best way to organize styles in a new Angular project? It would be nice to have the sass file in the same folder as the component.</p>
<blockquote>
<p><a target="_blank" href="https://stackoverflow.com/users/6265549"><strong><em>Mertcan Diken</em></strong></a> <strong><em>answered, (323+ points)</em></strong></p>
</blockquote>
<p>When you are creating your project with angular cli try this:</p>
<pre><code class="lang-bash">ng new My_New_Project --style=sass
</code></pre>
<p>This generating all your components with predifined sass files.</p>
<p>If you want scss syntax create your project with :</p>
<pre><code class="lang-bash">ng new My_New_Project --style=scss
</code></pre>
<p>If you are changing your existing style in your project</p>
<pre><code class="lang-bash">ng <span class="hljs-built_in">set</span> defaults.styleExt scss
</code></pre>
<p>Cli handles the rest of it.</p>
<p><a target="_blank" href="https://stackoverflow.com/questions/36220256"><strong>Source</strong></a><br><strong><a class="post-section-overview" href="#599b">Top</a></strong></p>
<h3 id="heading-triggering-change-detection-manually-in-angular">Triggering change detection manually in Angular</h3>
<blockquote>
<p>186+ points _? 1<em>02,556+ viewed   
</em><a target="_blank" href="https://stackoverflow.com/users/515279/jz87"><strong>jz87</strong></a> <strong>asked,</strong>_</p>
</blockquote>
<p>I’m writing an Angular component that has a property <code>Mode(): string</code>. I would like to be able to set this property programmatically not in response to any event. The problem is that in the absence of a browser event, a template binding <code>{{Mode}}</code> doesn't update. Is there a way to trigger this change detection manually?</p>
<blockquote>
<p><a target="_blank" href="https://stackoverflow.com/users/215945"><strong><em>Mark Rajcok</em></strong></a> <strong><em>answered, (345+ points)</em></strong></p>
</blockquote>
<p>Try one of these:</p>
<ul>
<li><code>[ApplicationRef.tick()](https://angular.io/docs/ts/latest/api/core/index/ApplicationRef-class.html#!#tick-anchor)</code> - similar to AngularJS's <code>$rootScope.$digest()</code> -- i.e., check the full component tree</li>
<li><code>[NgZone.run(callback)](https://angular.io/docs/ts/latest/api/core/index/NgZone-class.html#!#run-anchor)</code> - similar to <code>$rootScope.$apply(callback)</code> -- i.e., evaluate the callback function inside the Angular zone. I think, but I'm not sure, that this ends up checking the full component tree after executing the callback function.</li>
<li><code>[ChangeDetectorRef.detectChanges()](https://angular.io/docs/ts/latest/api/core/index/ChangeDetectorRef-class.html#!#detectChanges-anchor)</code> - similar to <code>$scope.$digest()</code> -- i.e., check only this component and its children</li>
</ul>
<p>You can inject <code>ApplicationRef</code>, <code>NgZone</code>, or <code>ChangeDetectorRef</code> into your component.</p>
<p><a target="_blank" href="https://stackoverflow.com/questions/34827334"><strong>Source</strong></a><br><strong><a class="post-section-overview" href="#599b">Top</a></strong></p>
<h3 id="heading-angular-and-typescript-cant-find-names">Angular and Typescript: Can’t find names</h3>
<blockquote>
<p>184+ points _? 1<em>81,472+ viewed   
</em><a target="_blank" href="https://stackoverflow.com/users/4997649/user233232"><strong>user233232</strong></a> <strong>asked,</strong>_</p>
</blockquote>
<p>I am using Angular (version 2) with TypeScript (version 1.6) and when I compile the code I get these errors:</p>
<pre><code class="lang-bash">Error TS2304: Cannot find name <span class="hljs-string">'Map'</span>.
    node_modules/angular2/src/core/change_detection/parser/locals.d.ts(4,42): Error TS2304: Cannot find name <span class="hljs-string">'Map'</span>.
    node_modules/angular2/src/core/facade/collection.d.ts(1,25): Error TS2304: Cannot find name <span class="hljs-string">'MapConstructor'</span>.
    node_modules/angular2/src/core/facade/collection.d.ts(2,25): Error TS2304: Cannot find name <span class="hljs-string">'SetConstructor'</span>.
    node_modules/angular2/src/core/facade/collection.d.ts(4,27): Error TS2304: Cannot find name <span class="hljs-string">'Map'</span>.
    node_modules/angular2/src/core/facade/collection.d.ts(4,39): Error TS2304: Cannot find name <span class="hljs-string">'Map'</span>.
    node_modules/angular2/src/core/facade/collection.d.ts(7,9): Error TS2304: Cannot find name <span class="hljs-string">'Map'</span>.
    node_modules/angular2/src/core/facade/collection.d.ts(8,30): Error TS2304: Cannot find name <span class="hljs-string">'Map'</span>.
    node_modules/angular2/src/core/facade/collection.d.ts(11,43): Error TS2304: Cannot find name <span class="hljs-string">'Map'</span>.
    node_modules/angular2/src/core/facade/collection.d.ts(12,27): Error TS2304: Cannot find name <span class="hljs-string">'Map'</span>.
    node_modules/angular2/src/core/facade/collection.d.ts(14,23): Error TS2304: Cannot find name <span class="hljs-string">'Map'</span>.
    node_modules/angular2/src/core/facade/collection.d.ts(15,25): Error TS2304: Cannot find name <span class="hljs-string">'Map'</span>.
    node_modules/angular2/src/core/facade/collection.d.ts(94,41): Error TS2304: Cannot find name <span class="hljs-string">'Set'</span>.
    node_modules/angular2/src/core/facade/collection.d.ts(95,22): Error TS2304: Cannot find name <span class="hljs-string">'Set'</span>.
    node_modules/angular2/src/core/facade/collection.d.ts(96,25): Error TS2304: Cannot find name <span class="hljs-string">'Set'</span>.
    node_modules/angular2/src/core/facade/lang.d.ts(1,22): Error TS2304: Cannot find name <span class="hljs-string">'BrowserNodeGlobal'</span>.
    node_modules/angular2/src/core/facade/lang.d.ts(33,59): Error TS2304: Cannot find name <span class="hljs-string">'Map'</span>.
    node_modules/angular2/src/core/facade/promise.d.ts(1,10): Error TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    node_modules/angular2/src/core/facade/promise.d.ts(3,14): Error TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    node_modules/angular2/src/core/facade/promise.d.ts(8,32): Error TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    node_modules/angular2/src/core/facade/promise.d.ts(9,38): Error TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    node_modules/angular2/src/core/facade/promise.d.ts(10,35): Error TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    node_modules/angular2/src/core/facade/promise.d.ts(10,93): Error TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    node_modules/angular2/src/core/facade/promise.d.ts(11,34): Error TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    node_modules/angular2/src/core/facade/promise.d.ts(12,32): Error TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    node_modules/angular2/src/core/facade/promise.d.ts(12,149): Error TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    node_modules/angular2/src/core/facade/promise.d.ts(13,43): Error TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    node_modules/angular2/src/core/linker/element_injector.d.ts(72,32): Error TS2304: Cannot find name <span class="hljs-string">'Map'</span>.
    node_modules/angular2/src/core/linker/element_injector.d.ts(74,17): Error TS2304: Cannot find name <span class="hljs-string">'Map'</span>.
    node_modules/angular2/src/core/linker/element_injector.d.ts(78,184): Error TS2304: Cannot find name <span class="hljs-string">'Map'</span>.
    node_modules/angular2/src/core/linker/element_injector.d.ts(83,182): Error TS2304: Cannot find name <span class="hljs-string">'Map'</span>.
    node_modules/angular2/src/core/linker/element_injector.d.ts(107,37): Error TS2304: Cannot find name <span class="hljs-string">'Map'</span>.
    node_modules/angular2/src/core/linker/proto_view_factory.d.ts(27,146): Error TS2304: Cannot find name <span class="hljs-string">'Map'</span>.
    node_modules/angular2/src/core/linker/view.d.ts(52,144): Error TS2304: Cannot find name <span class="hljs-string">'Map'</span>.
    node_modules/angular2/src/core/linker/view.d.ts(76,79): Error TS2304: Cannot find name <span class="hljs-string">'Map'</span>.
    node_modules/angular2/src/core/linker/view.d.ts(77,73): Error TS2304: Cannot find name <span class="hljs-string">'Map'</span>.
    node_modules/angular2/src/core/linker/view.d.ts(94,31): Error TS2304: Cannot find name <span class="hljs-string">'Map'</span>.
    node_modules/angular2/src/core/linker/view.d.ts(97,18): Error TS2304: Cannot find name <span class="hljs-string">'Map'</span>.
    node_modules/angular2/src/core/linker/view.d.ts(100,24): Error TS2304: Cannot find name <span class="hljs-string">'Map'</span>.
    node_modules/angular2/src/core/linker/view.d.ts(103,142): Error TS2304: Cannot find name <span class="hljs-string">'Map'</span>.
    node_modules/angular2/src/core/linker/view.d.ts(104,160): Error TS2304: Cannot find name <span class="hljs-string">'Map'</span>.
    node_modules/angular2/src/core/render/api.d.ts(281,74): Error TS2304: Cannot find name <span class="hljs-string">'Map'</span>.
    node_modules/angular2/src/core/zone/ng_zone.d.ts(1,37): Error TS2304: Cannot find name <span class="hljs-string">'Zone'</span>.
</code></pre>
<p>This is the code:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> <span class="hljs-string">'reflect-metadata'</span>;
<span class="hljs-keyword">import</span> {bootstrap, Component, CORE_DIRECTIVES, FORM_DIRECTIVES} <span class="hljs-keyword">from</span> <span class="hljs-string">'angular2/core'</span>;
<span class="hljs-meta">@Component</span>({
  selector: <span class="hljs-string">'my-app'</span>,
  template: <span class="hljs-string">'&lt;input type="text" [(ng-model)]="title" /&gt;&lt;h1&gt;{{title}}&lt;/h1&gt;'</span>,
  directives: [ CORE_DIRECTIVES ]
})
<span class="hljs-keyword">class</span> AppComponent {
  title :<span class="hljs-built_in">string</span>;

  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"></span>) {
    <span class="hljs-built_in">this</span>.title = <span class="hljs-string">'hello angular 2'</span>;
  }
}
bootstrap(AppComponent);
</code></pre>
<blockquote>
<p><a target="_blank" href="https://stackoverflow.com/users/390330"><strong><em>basarat</em></strong></a> <strong><em>answered, (50+ points)</em></strong></p>
</blockquote>
<p>A known issue: <a target="_blank" href="https://github.com/angular/angular/issues/4902">https://github.com/angular/angular/issues/4902</a></p>
<p>Core reason: the <code>.d.ts</code> file implicitly included by TypeScript varies with the compile target, so one needs to have more ambient declarations when targeting <code>es5</code> even if things are actually present in the runtimes (e.g. chrome). More on <code>[lib.d.ts](https://basarat.gitbooks.io/typescript/content/docs/types/lib.d.ts.html)</code></p>
<p><a target="_blank" href="https://stackoverflow.com/questions/33332394"><strong>Source</strong></a><br><strong><a class="post-section-overview" href="#599b">Top</a></strong></p>
<h3 id="heading-angular-what-is-the-meanings-of-moduleid-in-component">Angular — What is the meanings of module.id in component?</h3>
<blockquote>
<p>181+ points _? 5<em>4,337+ viewed   
</em><a target="_blank" href="https://stackoverflow.com/users/2837412/nishchit-dhanani"><strong>Nishchit Dhanani</strong></a> <strong>asked,</strong>_</p>
</blockquote>
<p>In an Angular app, I have seen that <code>@Component</code> has property <code>moduleId</code>. What does it mean?</p>
<p>And when <code>module.id</code> is not defined anywhere, the app still works. How can it still work?</p>
<pre><code class="lang-ts"><span class="hljs-meta">@Component</span>({
  moduleId: <span class="hljs-built_in">module</span>.id,
  selector: <span class="hljs-string">'ng-app'</span>,
  templateUrl: <span class="hljs-string">'app.component.html'</span>,
  styleUrls: [<span class="hljs-string">'app.component.css'</span>],
  directives: [AppComponent]
});
</code></pre>
<blockquote>
<p><a target="_blank" href="https://stackoverflow.com/users/2837412"><strong><em>Nishchit Dhanani</em></strong></a> <strong><em>answered, (145+ points)</em></strong></p>
</blockquote>
<p>The beta release of Angular (since vesion 2-alpha.51) supports relative assets for components, like <strong>templateUrl</strong> and <strong>styleUrls</strong> in the <code>@Component</code> decorator.</p>
<p><code>module.id</code> works when using CommonJS. You don't need to worry about how it works.</p>
<p><code>**Remember**: setting moduleId: module.id in the @Component decorator is the key here. If you don't have that then Angular 2 will be looking for your files at the root level.</code></p>
<p>Source from <a target="_blank" href="http://schwarty.com/2015/12/22/angular2-relative-paths-for-templateurl-and-styleurls/">Justin Schwartzenberger’s post</a>, thanks to <a target="_blank" href="https://stackoverflow.com/users/5043867/pardeep-jain">@Pradeep Jain</a></p>
<p><strong>Update on 16 Sep 2016:</strong></p>
<p><code>If you are using **webpack** for bundling then you don't need module.id in decorator. Webpack plugins auto handle (add it) module.id in final bundle</code></p>
<p><a target="_blank" href="https://stackoverflow.com/questions/37178192"><strong>Source</strong></a><br><strong><a class="post-section-overview" href="#599b">Top</a></strong></p>
<h3 id="heading-how-can-i-get-new-selection-in-select-in-angular-2">How can I get new selection in “select” in Angular 2?</h3>
<blockquote>
<p>175+ points _? 2<em>03,064+ viewed   
</em><a target="_blank" href="https://stackoverflow.com/users/2000548/hongbo-miao"><strong>Hongbo Miao</strong></a> <strong>asked,</strong>_</p>
</blockquote>
<p>I am using Angular 2 (TypeScript).</p>
<p>I want to do something for new selection, but what I got in onChange() is always last selection. How can I get new selection?</p>
<pre><code class="lang-ts">&lt;select [(ngModel)]=<span class="hljs-string">"selectedDevice"</span> (change)=<span class="hljs-string">"onChange($event)"</span>&gt;
    &lt;option *ngFor=<span class="hljs-string">"#i of devices"</span>&gt;{{i}}&lt;/option&gt;
&lt;/select&gt;

onChange($event) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.selectedDevice);
    <span class="hljs-comment">// I want to do something here for new selectedDevice, but what I</span>
    <span class="hljs-comment">// got here is always last selection, not the one I just select.</span>
}
</code></pre>
<blockquote>
<p><a target="_blank" href="https://stackoverflow.com/users/215945"><strong><em>Mark Rajcok</em></strong></a> <strong><em>answered, (370+ points)</em></strong></p>
</blockquote>
<p>If you don’t need two-way data-binding:</p>
<pre><code class="lang-ts">&lt;select (change)=<span class="hljs-string">"onChange($event.target.value)"</span>&gt;
    &lt;option *ngFor=<span class="hljs-string">"let i of devices"</span>&gt;{{i}}&lt;/option&gt;
&lt;/select&gt;

onChange(deviceValue) {
    <span class="hljs-built_in">console</span>.log(deviceValue);
}
</code></pre>
<p>For two-way data-binding, separate the event and property bindings:</p>
<pre><code class="lang-ts">&lt;select [ngModel]=<span class="hljs-string">"selectedDevice"</span> (ngModelChange)=<span class="hljs-string">"onChange($event)"</span> name=<span class="hljs-string">"sel2"</span>&gt;
    &lt;option [value]=<span class="hljs-string">"i"</span> *ngFor=<span class="hljs-string">"let i of devices"</span>&gt;{{i}}&lt;/option&gt;
&lt;/select&gt;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> AppComponent {
  devices = <span class="hljs-string">'one two three'</span>.split(<span class="hljs-string">' '</span>);
  selectedDevice = <span class="hljs-string">'two'</span>;
  onChange(newValue) {
    <span class="hljs-built_in">console</span>.log(newValue);
    <span class="hljs-built_in">this</span>.selectedDevice = newValue;
    <span class="hljs-comment">// ... do other stuff here ...</span>
}
</code></pre>
<p>If <code>devices</code> is array of objects, bind to <code>ngValue</code> instead of <code>value</code>:</p>
<pre><code class="lang-ts">&lt;select [ngModel]=<span class="hljs-string">"selectedDeviceObj"</span> (ngModelChange)=<span class="hljs-string">"onChangeObj($event)"</span> name=<span class="hljs-string">"sel3"</span>&gt;
  &lt;option [ngValue]=<span class="hljs-string">"i"</span> *ngFor=<span class="hljs-string">"let i of deviceObjects"</span>&gt;{{i.name}}&lt;/option&gt;
&lt;/select&gt;
{{selectedDeviceObj | json}}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> AppComponent {
  deviceObjects = [{name: <span class="hljs-number">1</span>}, {name: <span class="hljs-number">2</span>}, {name: <span class="hljs-number">3</span>}];
  selectedDeviceObj = <span class="hljs-built_in">this</span>.deviceObjects[<span class="hljs-number">1</span>];
  onChangeObj(newObj) {
    <span class="hljs-built_in">console</span>.log(newObj);
    <span class="hljs-built_in">this</span>.selectedDeviceObj = newObj;
    <span class="hljs-comment">// ... do other stuff here ...</span>
  }
}
</code></pre>
<p><a target="_blank" href="http://plnkr.co/edit/VbJUBkqAlS8UPVgh4bqV?p=preview">Plunker</a> — does not use <code>&lt;form&gt;</code><br><a target="_blank" href="http://plnkr.co/edit/pv5j4b1NFyTGFkxHUSga?p=preview">Plunker</a> - uses <code>&lt;form&gt;</code> and uses the new forms API</p>
<p><a target="_blank" href="https://stackoverflow.com/questions/33700266"><strong>Source</strong></a><br><strong><a class="post-section-overview" href="#599b">Top</a></strong></p>
<h3 id="heading-angular-exception-cant-bind-to-ngforin-since-it-isnt-a-known-native-property">Angular exception: Can’t bind to ‘ngForIn’ since it isn’t a known native property</h3>
<blockquote>
<p>172+ points _? 4<em>8,252+ viewed   
</em><a target="_blank" href="https://stackoverflow.com/users/215945/mark-rajcok"><strong>Mark Rajcok</strong></a> <strong>asked,</strong>_</p>
</blockquote>
<p>What am I doing wrong?</p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> {bootstrap, Component} <span class="hljs-keyword">from</span> <span class="hljs-string">'angular2/angular2'</span>

<span class="hljs-meta">@Component</span>({
  selector: <span class="hljs-string">'conf-talks'</span>,
  template: <span class="hljs-string">`&lt;div *ngFor="let talk in talks"&gt;
     {{talk.title}} by {{talk.speaker}}
     &lt;p&gt;{{talk.description}}
   &lt;/div&gt;`</span>
})
<span class="hljs-keyword">class</span> ConfTalks {
  talks = [ {title: <span class="hljs-string">'t1'</span>, speaker: <span class="hljs-string">'Brian'</span>, description: <span class="hljs-string">'talk 1'</span>},
            {title: <span class="hljs-string">'t2'</span>, speaker: <span class="hljs-string">'Julie'</span>, description: <span class="hljs-string">'talk 2'</span>}];
}
<span class="hljs-meta">@Component</span>({
  selector: <span class="hljs-string">'my-app'</span>,
  directives: [ConfTalks],
  template: <span class="hljs-string">'&lt;conf-talks&gt;&lt;/conf-talks&gt;'</span>
})
<span class="hljs-keyword">class</span> App {}
bootstrap(App, [])
</code></pre>
<p>The error is</p>
<pre><code class="lang-bash">EXCEPTION: Template parse errors:
Can<span class="hljs-string">'t bind to '</span>ngForIn<span class="hljs-string">' since it isn'</span>t a known native property
(<span class="hljs-string">"&lt;div [ERROR -&gt;]*ngFor="</span><span class="hljs-built_in">let</span> talk <span class="hljs-keyword">in</span> talks<span class="hljs-string">"&gt;</span>
</code></pre>
<blockquote>
<p><a target="_blank" href="https://stackoverflow.com/users/215945"><strong><em>Mark Rajcok</em></strong></a> <strong><em>answered, (403+ points)</em></strong></p>
</blockquote>
<p>Since this is at least the third time I’ve wasted more than 5 min on this problem I figured I’d post the Q &amp; A. I hope it helps someone else down the road… probably me!</p>
<p>I typed <code>in</code> instead of <code>of</code> in the ngFor expression.</p>
<p><strong>Befor 2-beta.17</strong>, it should be:</p>
<pre><code>&lt;div *ngFor=<span class="hljs-string">"#talk of talks"</span>&gt;
</code></pre><p><em>As of beta.17, use the <code>let</code> syntax instead of <code>#</code>. See the UPDATE further down for more info.</em></p>
<p>Note that the ngFor syntax “desugars” into the following:</p>
<pre><code class="lang-ts">&lt;template ngFor #talk [ngForOf]=<span class="hljs-string">"talks"</span>&gt;
  &lt;div&gt;...&lt;/div&gt;
&lt;/template&gt;
</code></pre>
<p>If we use <code>in</code> instead, it turns into</p>
<pre><code class="lang-ts">&lt;template ngFor #talk [ngForIn]=<span class="hljs-string">"talks"</span>&gt;
  &lt;div&gt;...&lt;/div&gt;
&lt;/template&gt;
</code></pre>
<p>Since <code>ngForIn</code> isn't an attribute directive with an input property of the same name (like <code>ngIf</code>), Angular then tries to see if it is a (known native) property of the <code>template</code> element, and it isn't, hence the error.</p>
<p><strong>UPDATE</strong> — as of 2-beta.17, use the <code>let</code> syntax instead of <code>#</code>. This updates to the following:</p>
<pre><code>&lt;div *ngFor=<span class="hljs-string">"let talk of talks"</span>&gt;
</code></pre><p>Note that the ngFor syntax “desugars” into the following:</p>
<pre><code class="lang-ts">&lt;template ngFor <span class="hljs-keyword">let</span>-talk [ngForOf]=<span class="hljs-string">"talks"</span>&gt;
  &lt;div&gt;...&lt;/div&gt;
&lt;/template&gt;
</code></pre>
<p>If we use <code>in</code> instead, it turns into</p>
<pre><code class="lang-ts">&lt;template ngFor <span class="hljs-keyword">let</span>-talk [ngForIn]=<span class="hljs-string">"talks"</span>&gt;
  &lt;div&gt;...&lt;/div&gt;
&lt;/template&gt;
</code></pre>
<p><a target="_blank" href="https://stackoverflow.com/questions/34561168"><strong>Source</strong></a><br><strong><a class="post-section-overview" href="#599b">Top</a></strong></p>
<h3 id="heading-ngif-and-ngfor-on-same-element-causing-error"><em>ngIf and </em>ngFor on same element causing error</h3>
<blockquote>
<p>171+ points _? 8<em>5,728+ viewed   
</em><strong><a target="_blank" href="https://stackoverflow.com/users/1128290/garethdn">garethdn</a> asked,</strong>_</p>
</blockquote>
<p>I’m having a problem with trying to use Angular’s <code>*ngFor</code> and <code>*ngIf</code> on the same element.</p>
<p>When trying to loop through the collection in the <code>*ngFor</code>, the collection is seen as <code>null</code> and consequently fails when trying to access its properties in the template.</p>
<pre><code class="lang-ts"><span class="hljs-meta">@Component</span>({
  selector: <span class="hljs-string">'shell'</span>,
  template: <span class="hljs-string">`
    &lt;h3&gt;Shell&lt;/h3&gt;&lt;button (click)="toggle()"&gt;Toggle!&lt;/button&gt;

    &lt;div *ngIf="show" *ngFor="let thing of stuff"&gt;
      {{log(thing)}}
      &lt;span&gt;{{thing.name}}&lt;/span&gt;
    &lt;/div&gt;
  `</span>
})

<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> ShellComponent <span class="hljs-keyword">implements</span> OnInit {

  <span class="hljs-keyword">public</span> stuff:<span class="hljs-built_in">any</span>[] = [];
  <span class="hljs-keyword">public</span> show:<span class="hljs-built_in">boolean</span> = <span class="hljs-literal">false</span>;

  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"></span>) {}

  ngOnInit() {
    <span class="hljs-built_in">this</span>.stuff = [
      { name: <span class="hljs-string">'abc'</span>, id: <span class="hljs-number">1</span> },
      { name: <span class="hljs-string">'huo'</span>, id: <span class="hljs-number">2</span> },
      { name: <span class="hljs-string">'bar'</span>, id: <span class="hljs-number">3</span> },
      { name: <span class="hljs-string">'foo'</span>, id: <span class="hljs-number">4</span> },
      { name: <span class="hljs-string">'thing'</span>, id: <span class="hljs-number">5</span> },
      { name: <span class="hljs-string">'other'</span>, id: <span class="hljs-number">6</span> },
    ]
  }

  toggle() {
    <span class="hljs-built_in">this</span>.show = !<span class="hljs-built_in">this</span>.show;
  }

  log(thing) {
    <span class="hljs-built_in">console</span>.log(thing);
  }

}
</code></pre>
<p>I know the easy solution is to move the <code>*ngIf</code> up a level but for scenarios like looping over list items in a <code>ul</code>, I'd end up with either an empty <code>li</code> if the collection is empty, or my <code>li</code>s wrapped in redundant container elements.</p>
<p>Example at this <a target="_blank" href="http://plnkr.co/edit/C5tZ8mD3iWczVvWkWycH?p=preview">plnkr</a>.</p>
<p>Note the console error:</p>
<p><code>EXCEPTION: TypeError: Cannot read property 'name' of null in [{{thing.name}} in ShellComponent@5:12]</code></p>
<p>Am I doing something wrong or is this a bug?</p>
<blockquote>
<p><a target="_blank" href="https://stackoverflow.com/users/217408"><strong><em>Günter Zöchbauer</em></strong></a> <strong><em>answered, (284+ points)</em></strong></p>
</blockquote>
<p>Angular2 doesn’t support more than one structural directive on the same element.<br>As a workaround use the <code>**&lt;ng-container&gt;**</code> element that allows you to use separate elements for each structural directive, but <strong>it is not stamped to the DOM</strong>.</p>
<pre><code class="lang-ts">&lt;ng-container *ngIf=<span class="hljs-string">"show"</span>&gt;
  &lt;div *ngFor=<span class="hljs-string">"let thing of stuff"</span>&gt;
    {{log(thing)}}
    &lt;span&gt;{{thing.name}}&lt;/span&gt;
  &lt;/div&gt;
&lt;/ng-container&gt;
</code></pre>
<p><code>&lt;ng-template&gt;</code> (<code>&lt;template&gt;</code> before Angular4) allows to do the same but with a different syntax which is confusing and no longer recommended</p>
<pre><code class="lang-ts">&lt;ng-template [ngIf]=<span class="hljs-string">"show"</span>&gt;
  &lt;div *ngFor=<span class="hljs-string">"let thing of stuff"</span>&gt;
    {{log(thing)}}
    &lt;span&gt;{{thing.name}}&lt;/span&gt;
  &lt;/div&gt;
&lt;/ng-template&gt;
</code></pre>
<p><a target="_blank" href="https://stackoverflow.com/questions/34657821"><strong>Source</strong></a><br><strong><a class="post-section-overview" href="#599b">Top</a></strong></p>
<h3 id="heading-what-is-the-angular-equivalent-to-an-angularjs-watch">What is the Angular equivalent to an AngularJS $watch?</h3>
<blockquote>
<p>169+ points _? 9<em>5,029+ viewed   
</em><a target="_blank" href="https://stackoverflow.com/users/1716567/erwin"><strong>Erwin</strong></a> <strong>asked,</strong>_</p>
</blockquote>
<p>In AngularJS you were able to specify watchers to observe changes in scope variables using the <code>$watch</code> function of the <code>$scope</code>. What is the equivalent of watching for variable changes (in, for example, component variables) in Angular?</p>
<blockquote>
<p><a target="_blank" href="https://stackoverflow.com/users/215945"><strong><em>Mark Rajcok</em></strong></a> <strong><em>answered, (226+ points)</em></strong></p>
</blockquote>
<p>In Angular 2, change detection is automatic… <code>$scope.$watch()</code> and <code>$scope.$digest()</code> R.I.P.</p>
<p>Unfortunately, the Change Detection section of the dev guide is not written yet (there is a placeholder near the bottom of the <a target="_blank" href="https://angular.io/docs/ts/latest/guide/architecture.html">Architecture Overview</a> page, in section “The Other Stuff”).</p>
<p>Here’s my understanding of how change detection works:</p>
<ul>
<li>Zone.js “monkey patches the world” — it intercepts all of the asynchronous APIs in the browser (when Angular runs). This is why we can use <code>setTimeout()</code> inside our components rather than something like <code>$timeout</code>... because <code>setTimeout()</code> is monkey patched.</li>
<li>Angular builds and maintains a tree of “change detectors”. There is one such change detector (class) per component/directive. (You can get access to this object by injecting <code>[ChangeDetectorRef](https://angular.io/docs/ts/latest/api/core/index/ChangeDetectorRef-class.html)</code>.) These change detectors are created when Angular creates components. They keep track of the state of all of your bindings, for dirty checking. These are, in a sense, similar to the automatic <code>$watches()</code> that Angular 1 would set up for <code>{{}}</code> template bindings.<br>Unlike Angular 1, the change detection graph is a directed tree and cannot have cycles (this makes Angular 2 much more performant, as we'll see below).</li>
<li>When an event fires (inside the Angular zone), the code we wrote (the event handler callback) runs. It can update whatever data it wants to — the shared application model/state and/or the component’s view state.</li>
<li>After that, because of the hooks Zone.js added, it then runs Angular’s change detection algorithm. By default (i.e., if you are not using the <code>onPush</code> change detection strategy on any of your components), every component in the tree is examined once (TTL=1)... from the top, in depth-first order. (Well, if you're in dev mode, change detection runs twice (TTL=2). See <a target="_blank" href="https://angular.io/docs/ts/latest/api/core/index/ApplicationRef-class.html#!#tick-anchor">ApplicationRef.tick()</a> for more about this.) It performs dirty checking on all of your bindings, using those change detector objects.</li>
<li>Lifecycle hooks are called as part of change detection.<br>If the component data you want to watch is a primitive input property (String, boolean, number), you can implement <code>ngOnChanges()</code> to be notified of changes.<br>If the input property is a reference type (object, array, etc.), but the reference didn't change (e.g., you added an item to an existing array), you'll need to implement <code>ngDoCheck()</code> (see <a target="_blank" href="https://stackoverflow.com/a/34298708/215945">this SO answer</a> for more on this).<br>You should only change the component's properties and/or properties of descendant components (because of the single tree walk implementation -- i.e., unidirectional data flow). Here's <a target="_blank" href="http://plnkr.co/edit/XWBSvE0NoQlRuOsXuOm0?p=preview">a plunker</a> that violates that. Stateful pipes can also <a target="_blank" href="https://stackoverflow.com/questions/34456430/ngfor-doesnt-update-data-with-pipe-in-angular2/34497504#34497504">trip you up</a> here.</li>
<li>For any binding changes that are found, the Components are updated, and then the DOM is updated. Change detection is now finished.</li>
<li>The browser notices the DOM changes and updates the screen.</li>
</ul>
<p>Other references to learn more:</p>
<ul>
<li><a target="_blank" href="https://blog.angularindepth.com/angulars-digest-is-reborn-in-the-newer-version-of-angular-718a961ebd3e">Angular’s $digest is reborn in the newer version of Angular</a> — explains how the ideas from AngularJS are mapped to Angular</li>
<li><a target="_blank" href="https://blog.angularindepth.com/everything-you-need-to-know-about-change-detection-in-angular-8006c51d206f">Everything you need to know about change detection in Angular</a> — explains in great detail how change detection works under the hood</li>
<li><a target="_blank" href="http://blog.thoughtram.io/angular/2016/02/22/angular-2-change-detection-explained.html">Change Detection Explained</a> — Thoughtram blog Feb 22, 2016 — probably the best reference out there</li>
<li>Savkin’s <a target="_blank" href="https://www.youtube.com/watch?v=jvKGQSFQf10">Change Detection Reinvented</a> video — definitely watch this one</li>
<li><a target="_blank" href="http://blog.jhades.org/how-does-angular-2-change-detection-really-work/">How does Angular 2 Change Detection Really Work?</a>- jhade’s blog Feb 24, 2016</li>
<li><a target="_blank" href="https://www.youtube.com/watch?v=3IqtmUscE_U">Brian’s video</a> and <a target="_blank" href="https://www.youtube.com/watch?v=V9Bbp6Hh2YE">Miško’s video</a> about Zone.js. Brian’s is about Zone.js. Miško’s is about how Angular 2 uses Zone.js to implement change detection. He also talks about change detection in general, and a little bit about <code>onPush</code>.</li>
<li>Victor Savkins blog posts: <a target="_blank" href="http://victorsavkin.com/post/110170125256/change-detection-in-angular-2">Change Detection in Angular 2</a>, <a target="_blank" href="http://victorsavkin.com/post/114168430846/two-phases-of-angular-2-applications">Two phases of Angular 2 applications</a>, <a target="_blank" href="http://victorsavkin.com/post/110170125256/change-detection-in-angular-2">Angular, Immutability and Encapsulation</a>. He covers a lot of ground quickly, but he can be terse at times, and you’re left scratching your head, wondering about the missing pieces.</li>
<li><a target="_blank" href="https://docs.google.com/document/d/1QKTbyVNPyRW-otJJVauON4TFMHpl0zNBPkJcTcfPJWg/edit">Ultra Fast Change Detection</a> (Google doc) — very technical, very terse, but it describes/sketches the ChangeDetection classes that get built as part of the tree</li>
</ul>
<p><a target="_blank" href="https://stackoverflow.com/questions/34569094"><strong>Source</strong></a><br><strong><a class="post-section-overview" href="#599b">Top</a></strong></p>
<h3 id="heading-importing-lodash-into-angular2-typescript-application">Importing lodash into angular2 + typescript application</h3>
<blockquote>
<p>167+ points _? 1<em>04,431+ viewed   
</em><a target="_blank" href="https://stackoverflow.com/users/1854793/davy"><strong>Davy</strong></a> <strong>asked,</strong>_</p>
</blockquote>
<p>I am having a hard time trying to get the lodash modules imported. I’ve setup my project using npm+gulp, and keep hitting the same wall. I’ve tried the regular lodash, but also lodash-es.</p>
<p>The lodash npm package: (has an index.js file in the package root folder)</p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> _ <span class="hljs-keyword">from</span> <span class="hljs-string">'lodash'</span>;
</code></pre>
<p>Results in:</p>
<pre><code>error TS2307: Cannot find <span class="hljs-built_in">module</span> <span class="hljs-string">'lodash'</span>.
</code></pre><p>The lodash-es npm package: (has a defaut export in lodash.js i the package root folder)</p>
<pre><code><span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> _ <span class="hljs-keyword">from</span> <span class="hljs-string">'lodash-es/lodash'</span>;
</code></pre><p>Results in:</p>
<pre><code>error TS2307: Cannot find <span class="hljs-built_in">module</span> <span class="hljs-string">'lodash-es'</span>.
</code></pre><p>Both the gulp task and webstorm report the same issue.</p>
<p>Funny fact, this returns no error:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> <span class="hljs-string">'lodash-es/lodash'</span>;
</code></pre>
<p>… but of course there is no “_” …</p>
<p>My tsconfig.json file:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"compilerOptions"</span>: {
    <span class="hljs-attr">"target"</span>: <span class="hljs-string">"es5"</span>,
    <span class="hljs-attr">"module"</span>: <span class="hljs-string">"system"</span>,
    <span class="hljs-attr">"moduleResolution"</span>: <span class="hljs-string">"node"</span>,
    <span class="hljs-attr">"sourceMap"</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">"emitDecoratorMetadata"</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">"experimentalDecorators"</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">"removeComments"</span>: <span class="hljs-literal">false</span>,
    <span class="hljs-attr">"noImplicitAny"</span>: <span class="hljs-literal">false</span>
  },
  <span class="hljs-attr">"exclude"</span>: [
    <span class="hljs-string">"node_modules"</span>
  ]
}
</code></pre>
<p>My gulpfile.js:</p>
<pre><code class="lang-json">var gulp = require('gulp'),
    ts = require('gulp-typescript'),
    uglify = require('gulp-uglify'),
    sourcemaps = require('gulp-sourcemaps'),
    tsPath = 'app<span class="hljs-comment">/**/</span>*.ts';

gulp.task('ts', function () {
    var tscConfig = require('./tsconfig.json');

    gulp.src([tsPath])
        .pipe(sourcemaps.init())
        .pipe(ts(tscConfig.compilerOptions))
        .pipe(sourcemaps.write('./../js'));
});

gulp.task('watch', function() {
    gulp.watch([tsPath], ['ts']);
});

gulp.task('default', ['ts', 'watch']);
</code></pre>
<p>If i understand correctly, moduleResolution:’node’ in my tsconfig should point the import statements to the node_modules folder, where lodash and lodash-es are installed. I’ve also tried lots of different ways to import: absolute paths, relative paths, but nothing seems to work. Any ideas?</p>
<p>If necessary i can provide a small zip file to illustrate the problem.</p>
<blockquote>
<p><a target="_blank" href="https://stackoverflow.com/users/544130"><strong><em>Taytay</em></strong></a> <strong><em>answered, (293+ points)</em></strong></p>
</blockquote>
<p>Here is how to do this as of Typescript 2.0: (tsd and typings are being deprecated in favor of the following):</p>
<pre><code class="lang-bash">$ npm install --save lodash

<span class="hljs-comment"># This is the new bit here: </span>
$ npm install --save @types/lodash
</code></pre>
<p>Then, in your .ts file:</p>
<p>Either:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> _ <span class="hljs-keyword">from</span> <span class="hljs-string">"lodash"</span>;
</code></pre>
<p>Or (as suggested by @Naitik):</p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> _ <span class="hljs-keyword">from</span> <span class="hljs-string">"lodash"</span>;
</code></pre>
<p>I’m not positive what the difference is. We use and prefer the first syntax. However, some report that the first syntax doesn’t work for them, and someone else has commented that the latter syntax is incompatible with lazy loaded webpack modules. YMMV.</p>
<p>Edit on Feb 27th, 2017:</p>
<p>According to @Koert below, <code>import * as _ from "lodash";</code> is the only working syntax as of Typescript 2.2.1, lodash 4.17.4, and @types/lodash 4.14.53. He says that the other suggested import syntax gives the error "has no default export".</p>
<p><a target="_blank" href="https://stackoverflow.com/questions/34660265"><strong>Source</strong></a><br><strong><a class="post-section-overview" href="#599b">Top</a></strong></p>
<h3 id="heading-how-to-detect-a-route-change-in-angular">How to detect a route change in Angular?</h3>
<blockquote>
<p>160+ points _? 1<em>08,593+ viewed   
</em><a target="_blank" href="https://stackoverflow.com/users/1590389/angularm"><strong>AngularM</strong></a> <strong>asked,</strong>_</p>
</blockquote>
<p>I am looking to detect a route change in my <code>AppComponent</code>.</p>
<p>Thereafter I will check the global user token to see if he is logged in. Then I can redirect the user if he is not logged in.</p>
<blockquote>
<p><a target="_blank" href="https://stackoverflow.com/users/1048274"><strong><em>Ludohen</em></strong></a> <strong><em>answered, (223+ points)</em></strong></p>
</blockquote>
<p>In Angular 2 you can <code>subscribe</code> (Rx event) to a Router instance. So you can do things like</p>
<pre><code class="lang-ts"><span class="hljs-keyword">class</span> MyClass {
  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> router: Router</span>) {
    router.subscribe(<span class="hljs-function">(<span class="hljs-params">val</span>) =&gt;</span> <span class="hljs-comment">/*whatever*/</span>)
  }
}
</code></pre>
<p><strong>Edit</strong> (since rc.1)</p>
<pre><code class="lang-ts"><span class="hljs-keyword">class</span> MyClass {
  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> router: Router</span>) {
    router.changes.subscribe(<span class="hljs-function">(<span class="hljs-params">val</span>) =&gt;</span> <span class="hljs-comment">/*whatever*/</span>)
  }
}
</code></pre>
<p><strong>Edit 2</strong> (since 2.0.0)</p>
<p>see also : <a target="_blank" href="https://angular.io/api/router/RouterEvent">Router.events doc</a></p>
<pre><code class="lang-ts"><span class="hljs-keyword">class</span> MyClass {
  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> router: Router</span>) {
    router.events.subscribe(<span class="hljs-function">(<span class="hljs-params">val</span>) =&gt;</span> {
        <span class="hljs-comment">// see also </span>
        <span class="hljs-built_in">console</span>.log(val <span class="hljs-keyword">instanceof</span> NavigationEnd) 
    });
  }
}
</code></pre>
<p><a target="_blank" href="https://stackoverflow.com/questions/33520043"><strong>Source</strong></a><br><strong><a class="post-section-overview" href="#599b">Top</a></strong></p>
<h3 id="heading-global-events-in-angular">Global Events in Angular</h3>
<blockquote>
<p>157+ points _? 8<em>3,980+ viewed   
</em><a target="_blank" href="https://stackoverflow.com/users/3368477/skovmand"><strong>skovmand</strong></a> <strong>asked,</strong>_</p>
</blockquote>
<p>Is there no equivalent to <code>$scope.emit()</code> or <code>$scope.broadcast()</code> in Angular?</p>
<p>I know the <code>EventEmitter</code> functionality, but as far as I understand that will just emit an event to the parent HTML element.</p>
<p>What if I need to communicate between fx. siblings or between a component in the root of the DOM and an element nested several levels deep?</p>
<blockquote>
<p><a target="_blank" href="https://stackoverflow.com/users/3661630"><strong><em>pixelbits</em></strong></a> <strong><em>answered, (304+ points)</em></strong></p>
</blockquote>
<p>There is no equivalent to <code>$scope.emit()</code> or <code>$scope.broadcast()</code> from AngularJS. EventEmitter inside of a component comes close, but as you mentioned, it will only emit an event to the immediate parent component.</p>
<p>In Angular, there are other alternatives which I’ll try to explain below.</p>
<p>@Input() bindings allows the application model to be connected in a directed object graph (root to leaves). The default behavior of a component’s change detector strategy is to propagate all changes to an application model for all bindings from any connected component.</p>
<p>Aside: There are two types of models: View Models and Application Models. An application model is connected through @Input() bindings. A view model is a just a component property (not decorated with @Input()) which is bound in the component’s template.</p>
<p>To answer your questions:</p>
<p>What if I need to communicate between sibling components?</p>
<ol>
<li><strong>Shared Application Model</strong>: Siblings can communicate through a shared application model (just like angular 1). For example, when one sibling makes a change to a model, the other sibling that has bindings to the same model is automatically updated.</li>
<li><strong>Component Events</strong>: Child components can emit an event to the parent component using @Output() bindings. The parent component can handle the event, and manipulate the application model or it’s own view model. Changes to the Application Model are automatically propagated to all components that directly or indirectly bind to the same model.</li>
<li><strong>Service Events</strong>: Components can subscribe to service events. For example, two sibling components can subscribe to the same service event and respond by modifying their respective models. More on this below.</li>
</ol>
<p>How can I communicate between a Root component and a component nested several levels deep?</p>
<ol>
<li><strong>Shared Application Model</strong>: The application model can be passed from the Root component down to deeply nested sub-components through @Input() bindings. Changes to a model from any component will automatically propagate to all components that share the same model.</li>
<li><strong>Service Events</strong>: You can also move the EventEmitter to a shared service, which allows any component to inject the service and subscribe to the event. That way, a Root component can call a service method (typically mutating the model), which in turn emits an event. Several layers down, a grand-child component which has also injected the service and subscribed to the same event, can handle it. Any event handler that changes a shared Application Model, will automatically propagate to all components that depend on it. This is probably the closest equivalent to <code>$scope.broadcast()</code> from Angular 1. The next section describes this idea in more detail.</li>
</ol>
<p><strong>Example of an Observable Service that uses Service Events to Propagate Changes</strong></p>
<p>Here is an example of an observable service that uses service events to propagate changes. When a TodoItem is added, the service emits an event notifying its component subscribers.</p>
<pre><code class="lang-ts"><span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> TodoItem {
    <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">public</span> name: <span class="hljs-built_in">string</span>, <span class="hljs-keyword">public</span> done: <span class="hljs-built_in">boolean</span></span>) {
    }
}
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> TodoService {
    <span class="hljs-keyword">public</span> itemAdded$: EventEmitter&lt;TodoItem&gt;;
    <span class="hljs-keyword">private</span> todoList: TodoItem[] = [];

    <span class="hljs-keyword">constructor</span>(<span class="hljs-params"></span>) {
        <span class="hljs-built_in">this</span>.itemAdded$ = <span class="hljs-keyword">new</span> EventEmitter();
    }

    <span class="hljs-keyword">public</span> list(): TodoItem[] {
        <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.todoList;
    }

    <span class="hljs-keyword">public</span> add(item: TodoItem): <span class="hljs-built_in">void</span> {
        <span class="hljs-built_in">this</span>.todoList.push(item);
        <span class="hljs-built_in">this</span>.itemAdded$.emit(item);
    }
}
</code></pre>
<p>Here is how a root component would subscribe to the event:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> RootComponent {
    <span class="hljs-keyword">private</span> addedItem: TodoItem;
    <span class="hljs-keyword">constructor</span>(<span class="hljs-params">todoService: TodoService</span>) {
        todoService.itemAdded$.subscribe(<span class="hljs-function"><span class="hljs-params">item</span> =&gt;</span> <span class="hljs-built_in">this</span>.onItemAdded(item));
    }

    <span class="hljs-keyword">private</span> onItemAdded(item: TodoItem): <span class="hljs-built_in">void</span> {
        <span class="hljs-comment">// do something with added item</span>
        <span class="hljs-built_in">this</span>.addedItem = item;
    }
}
</code></pre>
<p>A child component nested several levels deep would subscribe to the event in the same way:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> GrandChildComponent {
    <span class="hljs-keyword">private</span> addedItem: TodoItem;
    <span class="hljs-keyword">constructor</span>(<span class="hljs-params">todoService: TodoService</span>) {
        todoService.itemAdded$.subscribe(<span class="hljs-function"><span class="hljs-params">item</span> =&gt;</span> <span class="hljs-built_in">this</span>.onItemAdded(item));
    }

    <span class="hljs-keyword">private</span> onItemAdded(item: TodoItem): <span class="hljs-built_in">void</span> {
        <span class="hljs-comment">// do something with added item</span>
        <span class="hljs-built_in">this</span>.addedItem = item;
    }
}
</code></pre>
<p>Here is the component that calls the service to trigger the event (it can reside anywhere in the component tree):</p>
<pre><code class="lang-ts"><span class="hljs-meta">@Component</span>({
    selector: <span class="hljs-string">'todo-list'</span>,
    template: <span class="hljs-string">`
         &lt;ul&gt;
            &lt;li *ngFor="#item of model"&gt; {{ item.name }}
            &lt;/li&gt;
         &lt;/ul&gt;
        &lt;br /&gt;
        Add Item &lt;input type="text" #txt /&gt; &lt;button (click)="add(txt.value); txt.value='';"&gt;Add&lt;/button&gt;
    `</span>
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> TriggeringComponent{
    <span class="hljs-keyword">private</span> model: TodoItem[];

    <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> todoService: TodoService</span>) {
        <span class="hljs-built_in">this</span>.model = todoService.list();
    }

    add(value: <span class="hljs-built_in">string</span>) {
        <span class="hljs-built_in">this</span>.todoService.add(<span class="hljs-keyword">new</span> TodoItem(value, <span class="hljs-literal">false</span>));
    }
}
</code></pre>
<p>Reference: <a target="_blank" href="http://victorsavkin.com/post/110170125256/change-detection-in-angular-2">Change Detection in Angular</a></p>
<p><a target="_blank" href="https://stackoverflow.com/questions/34700438"><strong>Source</strong></a><br><strong><a class="post-section-overview" href="#599b">Top</a></strong></p>
<h3 id="heading-what-are-differences-between-systemjs-and-webpack">What are differences between SystemJS and Webpack?</h3>
<blockquote>
<p>155+ points _? 6<em>0,183+ viewed   
</em><a target="_blank" href="https://stackoverflow.com/users/2516399/smartmouse"><strong>smartmouse</strong></a> <strong>asked,</strong>_</p>
</blockquote>
<p>I’m creating my first Angular application and I would figure out what is the role of the module loaders. Why we need them? I tried to search and search on Google and I can’t understand why we need to install one of them to run our application?</p>
<p>Couldn’t it be enough to just use <code>import</code> to load stuff from node modules?</p>
<p>I have followed <a target="_blank" href="https://angular.io/docs/ts/latest/quickstart.html#!#systemjs">this tutorial</a> (that uses SystemJS) and it makes me to use <code>systemjs.config.js</code> file:</p>
<pre><code class="lang-js"><span class="hljs-comment">/**
 * System configuration for Angular samples
 * Adjust as necessary for your application needs.
 */</span>
(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">global</span>) </span>{
  <span class="hljs-comment">// map tells the System loader where to look for things</span>
  <span class="hljs-keyword">var</span> map = {
    <span class="hljs-string">'app'</span>:                        <span class="hljs-string">'transpiled'</span>, <span class="hljs-comment">// 'dist',</span>
    <span class="hljs-string">'@angular'</span>:                   <span class="hljs-string">'node_modules/@angular'</span>,
    <span class="hljs-string">'angular2-in-memory-web-api'</span>: <span class="hljs-string">'node_modules/angular2-in-memory-web-api'</span>,
    <span class="hljs-string">'rxjs'</span>:                       <span class="hljs-string">'node_modules/rxjs'</span>
  };
  <span class="hljs-comment">// packages tells the System loader how to load when no filename and/or no extension</span>
  <span class="hljs-keyword">var</span> packages = {
    <span class="hljs-string">'app'</span>:                        { <span class="hljs-attr">main</span>: <span class="hljs-string">'main.js'</span>,  <span class="hljs-attr">defaultExtension</span>: <span class="hljs-string">'js'</span> },
    <span class="hljs-string">'rxjs'</span>:                       { <span class="hljs-attr">defaultExtension</span>: <span class="hljs-string">'js'</span> },
    <span class="hljs-string">'angular2-in-memory-web-api'</span>: { <span class="hljs-attr">main</span>: <span class="hljs-string">'index.js'</span>, <span class="hljs-attr">defaultExtension</span>: <span class="hljs-string">'js'</span> },
  };
  <span class="hljs-keyword">var</span> ngPackageNames = [
    <span class="hljs-string">'common'</span>,
    <span class="hljs-string">'compiler'</span>,
    <span class="hljs-string">'core'</span>,
    <span class="hljs-string">'forms'</span>,
    <span class="hljs-string">'http'</span>,
    <span class="hljs-string">'platform-browser'</span>,
    <span class="hljs-string">'platform-browser-dynamic'</span>,
    <span class="hljs-string">'router'</span>,
    <span class="hljs-string">'router-deprecated'</span>,
    <span class="hljs-string">'upgrade'</span>,
  ];
  <span class="hljs-comment">// Individual files (~300 requests):</span>
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">packIndex</span>(<span class="hljs-params">pkgName</span>) </span>{
    packages[<span class="hljs-string">'@angular/'</span>+pkgName] = { <span class="hljs-attr">main</span>: <span class="hljs-string">'index.js'</span>, <span class="hljs-attr">defaultExtension</span>: <span class="hljs-string">'js'</span> };
  }
  <span class="hljs-comment">// Bundled (~40 requests):</span>
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">packUmd</span>(<span class="hljs-params">pkgName</span>) </span>{
    packages[<span class="hljs-string">'@angular/'</span>+pkgName] = { <span class="hljs-attr">main</span>: <span class="hljs-string">'/bundles/'</span> + pkgName + <span class="hljs-string">'.umd.js'</span>, <span class="hljs-attr">defaultExtension</span>: <span class="hljs-string">'js'</span> };
  }
  <span class="hljs-comment">// Most environments should use UMD; some (Karma) need the individual index files</span>
  <span class="hljs-keyword">var</span> setPackageConfig = System.packageWithIndex ? packIndex : packUmd;
  <span class="hljs-comment">// Add package entries for angular packages</span>
  ngPackageNames.forEach(setPackageConfig);
  <span class="hljs-keyword">var</span> config = {
    <span class="hljs-attr">map</span>: map,
    <span class="hljs-attr">packages</span>: packages
  };
  System.config(config);
})(<span class="hljs-built_in">this</span>);
</code></pre>
<p>Why we need this configuration file?<br>Why we need SystemJS (or WebPack or others)?<br>Finally, in your opinion what is the better?</p>
<blockquote>
<p><a target="_blank" href="https://stackoverflow.com/users/1873365"><strong><em>Thierry Templier</em></strong></a> <strong><em>answered, (97+ points)</em></strong></p>
</blockquote>
<p>If you go to the SystemJS Github page, you will see the description of the tool:</p>
<p><code>Universal dynamic module loader - loads ES6 modules, AMD, CommonJS and global scripts in the browser and NodeJS.</code></p>
<p>Because you use modules in TypeScript or ES6, you need a module loader. In the case of SystemJS, the <code>systemjs.config.js</code> allows us to configure the way in which module names are matched with their corresponding files.</p>
<p>This configuration file (and SystemJS) is necessary if you explicitly use it to import the main module of your application:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  System.import(<span class="hljs-string">'app'</span>).catch(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">err</span>)</span>{ <span class="hljs-built_in">console</span>.error(err); });
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<p>When using TypeScript, and configuring the compiler to the <code>commonjs</code> module, the compiler creates code that is no longer based on SystemJS. In this example, the typescript compiler config file would appear like this:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"compilerOptions"</span>: {
    <span class="hljs-attr">"target"</span>: <span class="hljs-string">"es5"</span>,
    <span class="hljs-attr">"module"</span>: <span class="hljs-string">"commonjs"</span>, <span class="hljs-comment">// &lt;------</span>
    <span class="hljs-attr">"moduleResolution"</span>: <span class="hljs-string">"node"</span>,
    <span class="hljs-attr">"sourceMap"</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">"emitDecoratorMetadata"</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">"experimentalDecorators"</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">"removeComments"</span>: <span class="hljs-literal">false</span>,
    <span class="hljs-attr">"noImplicitAny"</span>: <span class="hljs-literal">false</span>
  }
}
</code></pre>
<p>Webpack is a flexible module bundler. This means that it goes further and doesn’t only handle modules but also provides a way to package your application (concat files, uglify files, …). It also provides a dev server with load reload for development</p>
<p>SystemJS and Webpack are different but with SystemJS, you still have work to do (with <a target="_blank" href="http://gulpjs.com/">Gulp</a> or <a target="_blank" href="https://github.com/systemjs/builder">SystemJS builder</a> for example) to package your Angular2 application for production.</p>
<p><a target="_blank" href="https://stackoverflow.com/questions/38263406"><strong>Source</strong></a><br><strong><a class="post-section-overview" href="#599b">Top</a></strong></p>
<h3 id="heading-angular-cant-find-promise-map-set-and-iterator">Angular: Can’t find Promise, Map, Set and Iterator</h3>
<blockquote>
<p>154+ points _? 9<em>0,201+ viewed   
</em><a target="_blank" href="https://stackoverflow.com/users/806963/stav-alfi"><strong>Stav Alfi</strong></a> <strong>asked,</strong>_</p>
</blockquote>
<p>After installing Angular, the Typescript compiler keep getting some errors about not finding <code>Promise</code>, <code>Map</code>, <code>Set</code> and <code>Iterator</code>.</p>
<p>Until now I ignored them but now I need <code>Promise</code> so my code can work.</p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> {Component} <span class="hljs-keyword">from</span> <span class="hljs-string">'angular2/core'</span>;
<span class="hljs-meta">@Component</span>({
    selector: <span class="hljs-string">'greeting-cmp'</span>,
    template: <span class="hljs-string">`&lt;div&gt;{{ asyncGreeting | async}}&lt;/div&gt;`</span>
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> GreetingCmp {
    asyncGreeting: <span class="hljs-built_in">Promise</span>&lt;<span class="hljs-built_in">string</span>&gt; = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-params">resolve</span> =&gt;</span> {
<span class="hljs-comment">// after 1 second, the promise will resolve</span>
        <span class="hljs-built_in">window</span>.setTimeout(<span class="hljs-function">() =&gt;</span> resolve(<span class="hljs-string">'hello'</span>), <span class="hljs-number">1000</span>);
    });
}

Additional information:
npm -v is <span class="hljs-number">2.14</span><span class="hljs-number">.12</span>
node -v is v4<span class="hljs-number">.3</span><span class="hljs-number">.1</span>
typescript v is <span class="hljs-number">1.6</span>
</code></pre>
<p><strong>The errors:</strong></p>
<pre><code class="lang-bash">................ERROS OF MY CODE.................
    C:\Users\armyTik\Desktop\angular2\greeting_cmp.ts
    Error:(7, 20) TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    Error:(7, 42) TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    .........................................
    C:\Users\armyTik\Desktop\angular2\node_modules\angular2\platform\browser.d.ts
    Error:(77, 90) TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    C:\Users\armyTik\Desktop\angular2\node_modules\angular2\src\core\application_ref.d.ts
    Error:(83, 60) TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    Error:(83, 146) TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    Error:(96, 51) TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    Error:(96, 147) TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    Error:(133, 90) TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    Error:(171, 81) TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    C:\Users\armyTik\Desktop\angular2\node_modules\angular2\src\core\change_detection\parser\locals.d.ts
    Error:(3, 14) TS2304: Cannot find name <span class="hljs-string">'Map'</span>.
    Error:(4, 42) TS2304: Cannot find name <span class="hljs-string">'Map'</span>.
    C:\Users\armyTik\Desktop\angular2\node_modules\angular2\src\core\debug\debug_node.d.ts
    Error:(14, 13) TS2304: Cannot find name <span class="hljs-string">'Map'</span>.
    Error:(24, 17) TS2304: Cannot find name <span class="hljs-string">'Map'</span>.
    Error:(25, 17) TS2304: Cannot find name <span class="hljs-string">'Map'</span>.
    C:\Users\armyTik\Desktop\angular2\node_modules\angular2\src\core\di\provider.d.ts
    Error:(436, 103) TS2304: Cannot find name <span class="hljs-string">'Map'</span>.
    Error:(436, 135) TS2304: Cannot find name <span class="hljs-string">'Map'</span>.
    C:\Users\armyTik\Desktop\angular2\node_modules\angular2\src\core\linker\compiler.d.ts
    Error:(12, 50) TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    Error:(16, 41) TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    C:\Users\armyTik\Desktop\angular2\node_modules\angular2\src\core\linker\dynamic_component_loader.d.ts
    Error:(108, 136) TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    Error:(156, 150) TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    Error:(197, 128) TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    Error:(203, 127) TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    Error:(204, 141) TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    Error:(205, 119) TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    C:\Users\armyTik\Desktop\angular2\node_modules\angular2\src\core\render\api.d.ts
    Error:(13, 13) TS2304: Cannot find name <span class="hljs-string">'Map'</span>.
    Error:(14, 84) TS2304: Cannot find name <span class="hljs-string">'Map'</span>.
    C:\Users\armyTik\Desktop\angular2\node_modules\angular2\src\facade\async.d.ts
    Error:(27, 33) TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    Error:(28, 45) TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    C:\Users\armyTik\Desktop\angular2\node_modules\angular2\src\facade\collection.d.ts
    Error:(1, 25) TS2304: Cannot find name <span class="hljs-string">'MapConstructor'</span>.
    Error:(2, 25) TS2304: Cannot find name <span class="hljs-string">'SetConstructor'</span>.
    Error:(4, 27) TS2304: Cannot find name <span class="hljs-string">'Map'</span>.
    Error:(4, 39) TS2304: Cannot find name <span class="hljs-string">'Map'</span>.
    Error:(7, 9) TS2304: Cannot find name <span class="hljs-string">'Map'</span>.
    Error:(8, 30) TS2304: Cannot find name <span class="hljs-string">'Map'</span>.
    Error:(11, 43) TS2304: Cannot find name <span class="hljs-string">'Map'</span>.
    Error:(12, 27) TS2304: Cannot find name <span class="hljs-string">'Map'</span>.
    Error:(14, 23) TS2304: Cannot find name <span class="hljs-string">'Map'</span>.
    Error:(15, 25) TS2304: Cannot find name <span class="hljs-string">'Map'</span>.
    Error:(95, 41) TS2304: Cannot find name <span class="hljs-string">'Set'</span>.
    Error:(96, 22) TS2304: Cannot find name <span class="hljs-string">'Set'</span>.
    Error:(97, 25) TS2304: Cannot find name <span class="hljs-string">'Set'</span>.
    C:\Users\armyTik\Desktop\angular2\node_modules\angular2\src\facade\lang.d.ts
    Error:(13, 17) TS2304: Cannot find name <span class="hljs-string">'Map'</span>.
    Error:(14, 17) TS2304: Cannot find name <span class="hljs-string">'Set'</span>.
    Error:(78, 59) TS2304: Cannot find name <span class="hljs-string">'Map'</span>.
    C:\Users\armyTik\Desktop\angular2\node_modules\angular2\src\facade\promise.d.ts
    Error:(2, 14) TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    Error:(7, 32) TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    Error:(8, 38) TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    Error:(9, 35) TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    Error:(9, 93) TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    Error:(10, 34) TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    Error:(11, 32) TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    Error:(11, 149) TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    Error:(12, 43) TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    C:\Users\armyTik\Desktop\angular2\node_modules\angular2\src\http\headers.d.ts
    Error:(43, 59) TS2304: Cannot find name <span class="hljs-string">'Map'</span>.
    C:\Users\armyTik\Desktop\angular2\node_modules\angular2\src\http\url_search_params.d.ts
    Error:(11, 16) TS2304: Cannot find name <span class="hljs-string">'Map'</span>.
    C:\Users\armyTik\Desktop\angular2\node_modules\angular2\src\platform\browser\browser_adapter.d.ts
    Error:(75, 33) TS2304: Cannot find name <span class="hljs-string">'Map'</span>.
    C:\Users\armyTik\Desktop\angular2\node_modules\angular2\src\platform\dom\dom_adapter.d.ts
    Error:(85, 42) TS2304: Cannot find name <span class="hljs-string">'Map'</span>.
    C:\Users\armyTik\Desktop\angular2\node_modules\rxjs\CoreOperators.d.ts
    Error:(35, 67) TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    Error:(50, 66) TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    Error:(89, 67) TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    Error:(94, 38) TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    Error:(94, 50) TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    C:\Users\armyTik\Desktop\angular2\node_modules\rxjs\Observable.d.ts
    Error:(46, 62) TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    Error:(47, 42) TS2304: Cannot find name <span class="hljs-string">'Iterator'</span>.
    Error:(103, 74) TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    Error:(103, 84) TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    Error:(143, 66) TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    Error:(158, 65) TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    Error:(201, 66) TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    Error:(206, 38) TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    Error:(206, 50) TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    C:\Users\armyTik\Desktop\angular2\node_modules\rxjs\observable\ForkJoinObservable.d.ts
    Error:(6, 50) TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    Error:(7, 58) TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    C:\Users\armyTik\Desktop\angular2\node_modules\rxjs\observable\FromObservable.d.ts
    Error:(7, 38) TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    Error:(7, 51) TS2304: Cannot find name <span class="hljs-string">'Iterator'</span>.
    C:\Users\armyTik\Desktop\angular2\node_modules\rxjs\observable\PromiseObservable.d.ts
    Error:(9, 31) TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
    Error:(10, 26) TS2304: Cannot find name <span class="hljs-string">'Promise'</span>.
</code></pre>
<blockquote>
<p><a target="_blank" href="https://stackoverflow.com/users/1949099"><strong><em>Kris Hollenbeck</em></strong></a> <strong><em>answered, (162+ points)</em></strong></p>
</blockquote>
<h4 id="heading-angular-rc4-angular-200-with-typescript-200">Angular RC4 — Angular ^2.0.0 with Typescript 2.0.0</h4>
<p><em>Updated 9/19/2016</em></p>
<p>To get this to work with typescript 2.0.0, I did the following.</p>
<p><code>npm install --save-dev @types/core-js</code></p>
<p><strong>tsconfig.json</strong></p>
<pre><code class="lang-json"><span class="hljs-string">"compilerOptions"</span>: {
    <span class="hljs-attr">"declaration"</span>: <span class="hljs-literal">false</span>,
    <span class="hljs-attr">"emitDecoratorMetadata"</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">"experimentalDecorators"</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">"mapRoot"</span>: <span class="hljs-string">"./"</span>,
    <span class="hljs-attr">"module"</span>: <span class="hljs-string">"es6"</span>,
    <span class="hljs-attr">"moduleResolution"</span>: <span class="hljs-string">"node"</span>,
    <span class="hljs-attr">"noEmitOnError"</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">"noImplicitAny"</span>: <span class="hljs-literal">false</span>,
    <span class="hljs-attr">"outDir"</span>: <span class="hljs-string">"../dist/out-tsc"</span>,
    <span class="hljs-attr">"sourceMap"</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">"target"</span>: <span class="hljs-string">"es5"</span>,
    <span class="hljs-attr">"typeRoots"</span>: [
      <span class="hljs-string">"../node_modules/@types"</span>
    ],
    <span class="hljs-attr">"types"</span>: [
      <span class="hljs-string">"core-js"</span>
    ]
  }
</code></pre>
<p><strong>More about @types with typescript 2.0.0.</strong></p>
<ol>
<li><a target="_blank" href="https://blogs.msdn.microsoft.com/typescript/2016/06/15/the-future-of-declaration-files/">https://blogs.msdn.microsoft.com/typescript/2016/06/15/the-future-of-declaration-files/</a></li>
<li><a target="_blank" href="https://www.npmjs.com/~types">https://www.npmjs.com/~types</a></li>
</ol>
<p>Install Example:</p>
<pre><code>npm install --save-dev @types/core-js
</code></pre><p><strong>Duplicate Identifier errors</strong></p>
<p>This is most likely because duplicate ecmascript 6 typings are already being imported from somewhere else most likely an old es6-shim.</p>
<p>Double check <code>typings.d.ts</code> make sure there are no references to <code>es6</code>. Remove any reference to <code>es6</code> from your typings directory if you have one.</p>
<p><strong>For Example:</strong></p>
<p>This will conflict with <code>types:['core-js']</code> in typings.json.</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"globalDependencies"</span>: {
    <span class="hljs-attr">"core-js"</span>: <span class="hljs-string">"registry:dt/core-js#0.0.0+20160602141332"</span> 
    <span class="hljs-comment">// es6-shim will also conflict</span>
  }
}
</code></pre>
<p>Including <code>core-js</code> in the types array in <code>tsconfig.json</code> should be the only place it is imported from.</p>
<p><strong>Angular CLI 1.0.0-beta.30</strong></p>
<p>If you are using the Angular-CLI, remove the lib array in <code>typings.json</code>. This seems to conflict with declaring core-js in types.</p>
<pre><code class="lang-json"><span class="hljs-string">"compilerOptions"</span> : {
  ...
  <span class="hljs-comment">// removed "lib": ["es6", dom"],</span>
  ...
},
<span class="hljs-string">"types"</span> : [<span class="hljs-string">"core-js"</span>]
</code></pre>
<p><strong>Webstorm/Intellij Users using the Angular CLI</strong></p>
<p>Make sure the built in typescript compiler is disabled. This will conflict with the CLI. To compile your typescript with the CLI you can setup a <code>ng serve</code> configuration.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/YG2jiM4rYeIBDbXVSaDe3VOIdHlSAH1Z7hmN" alt="Image" width="800" height="448" loading="lazy"></p>
<p><strong>Tsconfig compilerOptions lib vs types</strong></p>
<p>If you prefer not to install core js type definitions there are some es6 libraries that come included with typescript. Those are used via the <code>lib: []</code> property in tsconfig.</p>
<p>See here for example: <a target="_blank" href="https://www.typescriptlang.org/docs/handbook/compiler-options.html">https://www.typescriptlang.org/docs/handbook/compiler-options.html</a></p>
<p><code>Note: If --lib is not specified a default library is injected. The default library injected is: ? For --target ES5: DOM,ES5,ScriptHost ? For --target ES6: DOM,ES6,DOM.Iterable,ScriptHost</code></p>
<p><strong>tl;dr</strong></p>
<p>Short answer either <code>"lib": [ "es6", "dom" ]</code> or <code>"types": ["core-js"]</code> can be used to resolve <code>can't find Promise,Map, Set and Iterator</code>. Using both however will cause duplicate identifier errors.</p>
<p><a target="_blank" href="https://stackoverflow.com/questions/35660498"><strong>Source</strong></a><br><strong><a class="post-section-overview" href="#599b">Top</a></strong></p>
<h3 id="heading-how-to-detect-when-an-input-value-changes-in-angular">How to detect when an @Input() value changes in Angular?</h3>
<blockquote>
<p>154+ points _? 8<em>9,893+ viewed   
</em><a target="_blank" href="https://stackoverflow.com/users/3604283/jon-catmull"><strong>Jon Catmull</strong></a> <strong>asked,</strong>_</p>
</blockquote>
<p>I have a parent component (<strong>CategoryComponent</strong>), a child component (<strong>videoListComponent</strong>) and an ApiService.</p>
<p>I have most of this working fine i.e. each component can access the json api and get its relevant data via observables.</p>
<p>Currently video list component just gets all videos, I would like to filter this to just videos in a particular category, I achieved this by passing the categoryId to the child via <code>@Input()</code>.</p>
<p>CategoryComponent.html</p>
<pre><code class="lang-ts">&lt;video-list *ngIf=<span class="hljs-string">"category"</span> [categoryId]=<span class="hljs-string">"category.id"</span>&gt;&lt;/video-list&gt;
</code></pre>
<p>This works and when the parent CategoryComponent category changes then the categoryId value gets passed through via <code>@Input()</code> but I then need to detect this in VideoListComponent and re-request the videos array via APIService (with the new categoryId).</p>
<p>In AngularJS I would have done a <code>$watch</code> on the variable. What is the best way to handle this?</p>
<blockquote>
<p><a target="_blank" href="https://stackoverflow.com/users/2107767"><strong><em>Alan C. S.</em></strong></a> <strong><em>answered, (181+ points)</em></strong></p>
</blockquote>
<p><strong>Actually, there are two ways of detecting and acting up on when an input changes in the child component in angular2+ :</strong></p>
<ol>
<li>You can use the <strong>ngOnChanges() lifecycle method</strong> as also mentioned in older answers:<br><code>@Input() categoryId: string; ngOnChanges(changes: SimpleChanges) { this.doSomething(changes.categoryId.currentValue); // You can also use categoryId.previousValue and // categoryId.firstChange for comparing old and new values }</code></li>
<li>Documentation Links: <a target="_blank" href="https://angular.io/api/core/OnChanges">ngOnChanges,</a> <a target="_blank" href="https://angular.io/api/core/SimpleChanges">SimpleChanges,</a> <a target="_blank" href="https://angular.io/api/core/SimpleChange">SimpleChange</a><br>Demo Example: Look at <a target="_blank" href="https://plnkr.co/edit/LUr2bMQRhhAeuLN3R5B6?p=preview">this plunker</a></li>
<li>Alternately, you can also use an <strong>input property setter</strong> as follows:<br><code>private _categoryId: string; @Input() set categoryId(value: string) { this._categoryId = value; this.doSomething(this._categoryId); } get categoryId(): string { return this._categoryId; }</code></li>
<li>Documentation Link: Look <a target="_blank" href="https://angular.io/guide/component-interaction#intercept-input-property-changes-with-a-setter">here</a>.</li>
<li>Demo Example: Look at <a target="_blank" href="https://plnkr.co/edit/EsolgwJVuvOUx6rKk8d4?p=preview">this plunker</a>.</li>
</ol>
<p><strong>WHICH APPROACH SHOULD YOU USE?</strong></p>
<p>If your component has several inputs, then, if you use ngOnChanges(), you will get all changes for all the inputs at once within ngOnChanges(). Using this approach, you can also compare current and previous values of the input that has changed and take actions accordingly.</p>
<p>However, if you want to do something when only a particular single input changes (and you don’t care about the other inputs), then it might be simpler to use an input property setter. However, this approach does not provide a built in way to compare previous and current values of the changed input (which you can do easily with the ngOnChanges lifecycle method).</p>
<p><strong>EDIT 2017–07–25: ANGULAR CHANGE DETECTION MAY STILL NOT FIRE UNDER SOME CIRCUMSTANCES</strong></p>
<p>Normally, change detection for both setter and ngOnChanges will fire whenever the parent component changes the data it passes to the child, <strong>provided that the data is a JS primitive datatype(string, number, boolean)</strong>. However, in the following scenarios, it will not fire and you have to take extra actions in order to make it work.</p>
<ol>
<li>If you are using a nested object or array (instead of a JS primitive data type) to pass data from Parent to Child, change detection (using either setter or ngchanges) might not fire, as also mentioned in the answer by user: muetzerich. For solutions look <a target="_blank" href="https://stackoverflow.com/questions/34796901/angular2-change-detection-ngonchanges-not-firing-for-nested-object">here</a>.</li>
<li>If you are mutating data outside of the angular context (i.e., externally), then angular will not know of the changes. You may have to use ChangeDetectorRef or NgZone in your component for making angular aware of external changes and thereby triggering change detection. Refer to <a target="_blank" href="https://stackoverflow.com/questions/42971865/angular2-zone-run-vs-changedetectorref-detectchanges">this</a>.</li>
</ol>
<p><a target="_blank" href="https://stackoverflow.com/questions/38571812"><strong>Source</strong></a><br><strong><a class="post-section-overview" href="#599b">Top</a></strong></p>
<h3 id="heading-how-to-pass-url-arguments-query-string-to-a-http-request-on-angular">How to pass URL arguments (query string) to a HTTP request on Angular</h3>
<blockquote>
<p>154+ points _? 1<em>57,619+ viewed   
</em><a target="_blank" href="https://stackoverflow.com/users/3276721/miguel-lattuada"><strong>Miguel Lattuada</strong></a> <strong>asked,</strong>_</p>
</blockquote>
<p>Hi guys I’m creating a HTTP request on Angular, but I do not know how to add URL arguments (query string) to it.</p>
<pre><code class="lang-ts"><span class="hljs-built_in">this</span>.http.get(StaticSettings.BASE_URL).subscribe(
  <span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> <span class="hljs-built_in">this</span>.onGetForecastResult(response.json()),
  <span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> <span class="hljs-built_in">this</span>.onGetForecastError(error.json()),
  <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">this</span>.onGetForecastComplete()
);
</code></pre>
<p>Now my StaticSettings.BASE_URL is something like a url with no query string like: <a target="_blank" href="http://atsomeplace.com/">http://atsomeplace.com/</a> but I want it to be <a target="_blank" href="http://atsomeplace.com/?var1=val1&amp;var2=val2">http://atsomeplace.com/?var1=val1&amp;var2=val2</a></p>
<p>Where var1, and var2 fit on my Http request object? I want to add them like an object.</p>
<pre><code class="lang-json">{
  query: {
    var1: val1,
    var2: val2
  }
}
</code></pre>
<p>and then just the Http module do the job to parse it into URL query string.</p>
<blockquote>
<p><a target="_blank" href="https://stackoverflow.com/users/5152732"><strong><em>toskv</em></strong></a> <strong><em>answered, (216+ points)</em></strong></p>
</blockquote>
<p>The <a target="_blank" href="https://angular.io/api/common/http/HttpClient"><strong>HttpClient</strong></a> methods allow you to set the <strong>params</strong> in it’s options.</p>
<p>You can configure it by importing the <a target="_blank" href="https://angular.io/api/common/http"><strong>HttpClientModule</strong></a> from the @angular/common/http package.</p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> {HttpClientModule} <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/common/http'</span>;

<span class="hljs-meta">@NgModule</span>({
  imports: [ BrowserModule, HttpClientModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> AppModule {}
</code></pre>
<p>After that you can inject the <strong>HttpClient</strong> and use it to do the request.</p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> {HttpClient} <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/common/http'</span>
</code></pre>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> {HttpClient} <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/common/http'</span>

<span class="hljs-meta">@Component</span>({
  selector: <span class="hljs-string">'my-app'</span>,
  template: <span class="hljs-string">`
    &lt;div&gt;
      &lt;h2&gt;Hello {{name}}&lt;/h2&gt;
    &lt;/div&gt;
  `</span>,
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> App {
  name:<span class="hljs-built_in">string</span>;
  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> httpClient: HttpClient</span>) {
    <span class="hljs-built_in">this</span>.httpClient.get(<span class="hljs-string">'/url'</span>, {
      params: {
        appid: <span class="hljs-string">'id1234'</span>,
        cnt: <span class="hljs-string">'5'</span>
      },
      observe: <span class="hljs-string">'response'</span>
    })
    .toPromise()
    .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> {
      <span class="hljs-built_in">console</span>.log(response);
    })
    .catch(<span class="hljs-built_in">console</span>.log);
  }
}
</code></pre>
<p>You can find a working example <a target="_blank" href="https://plnkr.co/edit/G4mczOLOHfVYKpuaWee3?p=preview">here</a>.</p>
<p>For angular versions prior to version 4 you can do the same using the <strong>Http</strong> service.</p>
<p>The <strong>Http.get</strong> method takes an object that implements <a target="_blank" href="https://angular.io/docs/ts/latest/api/http/index/RequestOptionsArgs-interface.html">RequestOptionsArgs</a> as a second parameter.</p>
<p>The <strong>search</strong> field of that object can be used to set a string or a <a target="_blank" href="https://angular.io/docs/ts/latest/api/http/index/URLSearchParams-class.html">URLSearchParams</a> object.</p>
<p>An example:</p>
<pre><code class="lang-ts"><span class="hljs-comment">// Parameters obj-</span>
 <span class="hljs-keyword">let</span> params: URLSearchParams = <span class="hljs-keyword">new</span> URLSearchParams();
 params.set(<span class="hljs-string">'appid'</span>, StaticSettings.API_KEY);
 params.set(<span class="hljs-string">'cnt'</span>, days.toString());

 <span class="hljs-comment">//Http request-</span>
 <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.http.get(StaticSettings.BASE_URL, {
   search: params
 }).subscribe(
   <span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> <span class="hljs-built_in">this</span>.onGetForecastResult(response.json()), 
   <span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> <span class="hljs-built_in">this</span>.onGetForecastError(error.json()), 
   <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">this</span>.onGetForecastComplete()
 );
</code></pre>
<p>The documentation for the <strong>Http</strong> class has more details. It can be found <a target="_blank" href="https://angular.io/docs/ts/latest/api/http/index/Http-class.html">here</a> and an working example <a target="_blank" href="https://plnkr.co/edit/pKdztZBHr0wr1YLmmI8P?p=preview">here</a>.</p>
<p><a target="_blank" href="https://stackoverflow.com/questions/34475523"><strong>Source</strong></a><br><strong><a class="post-section-overview" href="#599b">Top</a></strong></p>
<h3 id="heading-how-do-you-deploy-angular-apps">How do you deploy Angular apps?</h3>
<blockquote>
<p>153+ points _? 8<em>9,991+ viewed   
</em><a target="_blank" href="https://stackoverflow.com/users/1362355/joseph-girgis"><strong>Joseph Assem Sobhy</strong></a> <strong>asked,</strong>_</p>
</blockquote>
<p>How do you deploy Angular apps once they reach the production phase?</p>
<p>All the guides I’ve seen so far (even on <a target="_blank" href="https://angular.io/">angular.io</a>) are counting on a lite-server for serving and browserSync to reflect changes — but when you finish with development, how can you publish the app?</p>
<p>Do I import all the compiled <code>.js</code> files on the <code>index.html</code> page or do I minify them using gulp? Will they work? Do I need SystemJS at all in the production version?</p>
<blockquote>
<p><a target="_blank" href="https://stackoverflow.com/users/1035889"><strong><em>Amid</em></strong></a> <strong><em>answered, (74+ points)</em></strong></p>
</blockquote>
<p>You are actually here touching two questions in one. First one is how to host your application. And as @toskv mentioned its really too broad question to be answered and depends on numerous different things. Second one is more specific — how do you prepare the deployment version of the application. You have several options here:</p>
<ol>
<li>Deploy as it is. Just that — no minification, concatenation, name mangling etc. Transpile all your ts project, copy all your resulting js/css/… sources + dependencies to the hosting server and your are good to go.</li>
<li>Deploy using special bundling tools. Like webpack or systemjs builder. They come with all possibilities that are lacking in #1. You can pack all your app code into just couple of js/css/… files that you reference in your html. Systemjs buider even allows you to get rid of need to include systemjs as part of your deployment package.</li>
</ol>
<p>Yes you will most likely need to deploy systemjs and bunch of other external libraries as part of your package. And yes you will be able to bundle them into just couple of js files you reference from your html page. You do not have to reference all your compiled js files from the page though — systemjs as a module loader will take care of that.</p>
<p>I know it sounds muddy — to help get you started with the #2 here are two really good sample applications:</p>
<p>SystemJS builder: <a target="_blank" href="https://github.com/mgechev/angular2-seed">angular2 seed</a></p>
<p>WebPack: <a target="_blank" href="https://github.com/AngularClass/angular2-webpack-starter">angular2 webpack starter</a></p>
<p>Look how they do it — and hopefully this will help you to find your way of bundling apps you make.</p>
<p><a target="_blank" href="https://stackoverflow.com/questions/35539622"><strong>Source</strong></a><br><strong><a class="post-section-overview" href="#599b">Top</a></strong></p>
<h3 id="heading-ngfor-with-index-as-value-in-attribute">ngFor with index as value in attribute</h3>
<blockquote>
<p>149+ points _? 1<em>95,294+ viewed   
</em><a target="_blank" href="https://stackoverflow.com/users/1175327/vivendi"><strong>Vivendi</strong></a> <strong>asked,</strong>_</p>
</blockquote>
<p>I have a simple <code>ngFor</code> loop which also keeps track of the current <code>index</code>. I want to store that <code>index</code> value in an attribute so I can print it. But I can't figure out how this works.</p>
<p>I basically have this:</p>
<pre><code class="lang-ts">&lt;ul *ngFor=<span class="hljs-string">"#item of items; #i = index"</span> data-index=<span class="hljs-string">"#i"</span>&gt;
    &lt;li&gt;{{item}}&lt;/li&gt;
&lt;/ul&gt;
</code></pre>
<p>I want to store the value of <code>#i</code> in the attribute <code>data-index</code>. I tried several methods but none of them worked.</p>
<p>I have a demo here: <a target="_blank" href="http://plnkr.co/edit/EXpOKAEIFlI9QwuRcZqp?p=preview">http://plnkr.co/edit/EXpOKAEIFlI9QwuRcZqp?p=preview</a></p>
<p>How can I store the <code>index</code> value in the <code>data-index</code> attribute?</p>
<blockquote>
<p><a target="_blank" href="https://stackoverflow.com/users/1873365"><strong><em>Thierry Templier</em></strong></a> <strong><em>answered, (284+ points)</em></strong></p>
</blockquote>
<p>I would use this syntax to set the index value into an attribute of the HTML element:</p>
<pre><code class="lang-ts">&lt;ul&gt;
    &lt;li *ngFor=<span class="hljs-string">"#item of items; #i = index"</span> [attr.data-index]=<span class="hljs-string">"i"</span>&gt;
        {{item}}
    &lt;/li&gt;
&lt;/ul&gt;
</code></pre>
<p>Here is the updated plunkr: <a target="_blank" href="http://plnkr.co/edit/LiCeyKGUapS5JKkRWnUJ?p=preview">http://plnkr.co/edit/LiCeyKGUapS5JKkRWnUJ?p=preview</a>.</p>
<p><strong>Update for recent angular 2 releases</strong> You have to use <code>let</code> to declare the value rather than <code>#</code>.</p>
<pre><code class="lang-ts">&lt;ul&gt;
    &lt;li *ngFor=<span class="hljs-string">"let item of items; let i = index"</span> [attr.data-index]=<span class="hljs-string">"i"</span>&gt;
        {{item}}
    &lt;/li&gt;
&lt;/ul&gt;
</code></pre>
<p><a target="_blank" href="https://stackoverflow.com/questions/35405618"><strong>Source</strong></a><br><strong><a class="post-section-overview" href="#599b">Top</a></strong></p>
<h3 id="heading-define-global-constants-in-angular-2">Define global constants in Angular 2</h3>
<blockquote>
<p>149+ points _? 1<em>28,101+ viewed   
</em><a target="_blank" href="https://stackoverflow.com/users/2946773/andrefeijo"><strong>AndreFeijo</strong></a> <strong>asked,</strong>_</p>
</blockquote>
<p>In Angular 1.x you can define constants like this:</p>
<pre><code class="lang-ts">angular.module(<span class="hljs-string">'mainApp.config'</span>, [])
.constant(<span class="hljs-string">'API_ENDPOINT'</span>, <span class="hljs-string">'http://127.0.0.1:6666/api/'</span>)
</code></pre>
<p>What would be the equivalent in Angular2 (with Typescript)? I just don’t want to repeat the API base url over and over again in all my services.</p>
<blockquote>
<p><a target="_blank" href="https://stackoverflow.com/users/2946773"><strong><em>AndreFeijo</em></strong></a> <strong><em>answered, (159+ points)</em></strong></p>
</blockquote>
<p><strong>Below changes works for me on Angular 2 final version:</strong></p>
<pre><code class="lang-ts"><span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> AppSettings {
   <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> API_ENDPOINT=<span class="hljs-string">'http://127.0.0.1:6666/api/'</span>;
}
</code></pre>
<p><strong>And then in the service:</strong></p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> {Http} <span class="hljs-keyword">from</span> <span class="hljs-string">'angular2/http'</span>;
<span class="hljs-keyword">import</span> {Message} <span class="hljs-keyword">from</span> <span class="hljs-string">'../models/message'</span>;
<span class="hljs-keyword">import</span> {Injectable} <span class="hljs-keyword">from</span> <span class="hljs-string">'angular2/core'</span>;
<span class="hljs-keyword">import</span> {Observable} <span class="hljs-keyword">from</span> <span class="hljs-string">'rxjs/Observable'</span>;
<span class="hljs-keyword">import</span> {AppSettings} <span class="hljs-keyword">from</span> <span class="hljs-string">'../appSettings'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'rxjs/add/operator/map'</span>;

<span class="hljs-meta">@Injectable</span>()
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> MessageService {

    <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> http: Http</span>) { }

    getMessages(): Observable&lt;Message[]&gt; {
        <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.http.get(AppSettings.API_ENDPOINT+<span class="hljs-string">'/messages'</span>)
            .map(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json())
            .map(<span class="hljs-function">(<span class="hljs-params">messages: <span class="hljs-built_in">Object</span>[]</span>) =&gt;</span> {
                <span class="hljs-keyword">return</span> messages.map(<span class="hljs-function"><span class="hljs-params">message</span> =&gt;</span> <span class="hljs-built_in">this</span>.parseData(message));
            });
    }

    <span class="hljs-keyword">private</span> parseData(data): Message {
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Message(data);
    }
}
</code></pre>
<p><a target="_blank" href="https://stackoverflow.com/questions/34986922"><strong>Source</strong></a><br><strong><a class="post-section-overview" href="#599b">Top</a></strong></p>
<h3 id="heading-angular-use-pipes-in-services-and-components">Angular — Use pipes in services and components</h3>
<blockquote>
<p>148+ points _? 7<em>5,716+ viewed   
</em><a target="_blank" href="https://stackoverflow.com/users/4602586/posix-compliant"><strong>POSIX-compliant</strong></a> <strong>asked,</strong>_</p>
</blockquote>
<p>In AngularJS, I am able to use filters (pipes) inside of services and controllers using syntax similar to this:</p>
<pre><code class="lang-ts">$filter(<span class="hljs-string">'date'</span>)(myDate, <span class="hljs-string">'yyyy-MM-dd'</span>);
</code></pre>
<p>Is it possible to use pipes in services/components like this in Angular?</p>
<blockquote>
<p><a target="_blank" href="https://stackoverflow.com/users/971121"><strong><em>cexbrayat</em></strong></a> <strong><em>answered, (271+ points)</em></strong></p>
</blockquote>
<p>As usual in Angular, you can rely on dependency injection:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> { DatePipe } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/common'</span>;
<span class="hljs-keyword">class</span> MyService {

  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> datePipe: DatePipe</span>) {}

  transformDate(date) {
    <span class="hljs-built_in">this</span>.datePipe.transform(myDate, <span class="hljs-string">'yyyy-MM-dd'</span>);
  }
}
</code></pre>
<p>Add <code>DatePipe</code> to your providers list in your module; if you forget to do this you'll get an error <code>no provider for DatePipe</code>:</p>
<pre><code>providers: [DatePipe,...]
</code></pre><p>Be warned though that the <code>DatePipe</code> was relying on the Intl API until version 5, which is not supported by all browsers (check the <a target="_blank" href="http://kangax.github.io/compat-table/esintl/">compatibility table</a>).</p>
<p>If you’re using older Angular versions, you should add the <code>Intl</code> polyfill to your project to avoid any problem. See this <a target="_blank" href="https://stackoverflow.com/questions/35017800/ionic-2-using-angular-2-pipe-breaks-on-ios-cant-find-variable-intl/35018352#35018352">related question</a> for a more detailed answer.</p>
<p><a target="_blank" href="https://stackoverflow.com/questions/35144821"><strong>Source</strong></a><br><strong><a class="post-section-overview" href="#599b">Top</a></strong></p>
<h3 id="heading-angular2-exception-cant-bind-to-routerlink-since-it-isnt-a-known-native-property">Angular2 Exception: Can’t bind to ‘routerLink’ since it isn’t a known native property</h3>
<blockquote>
<p>144+ points _? 8<em>3,326+ viewed   
</em><a target="_blank" href="https://stackoverflow.com/users/1798547/lester-burnham"><strong>Lester Burnham</strong></a> <strong>asked,</strong>_</p>
</blockquote>
<p>Obviously the beta for Angular2 is newer than new, so there’s not much information out there, but I am trying to do what I think is some fairly basic routing.</p>
<p>Hacking about with the quick-start code and other snippets from the <a target="_blank" href="https://angular.io">https://angular.io</a> website has resulted in the following file structure:</p>
<pre><code>angular-testapp/
    app/
        app.component.ts
        boot.ts
        routing-test.component.ts
    index.html
</code></pre><p>With the files being populated as follows:</p>
<p><strong>index.html</strong></p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">base</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Angular 2 QuickStart<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"../css/bootstrap.css"</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span>&gt;</span>

    <span class="hljs-comment">&lt;!-- 1. Load libraries --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"node_modules/angular2/bundles/angular2-polyfills.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"node_modules/systemjs/dist/system.src.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"node_modules/rxjs/bundles/Rx.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"node_modules/angular2/bundles/angular2.dev.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"node_modules/angular2/bundles/router.dev.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>

    <span class="hljs-comment">&lt;!-- 2. Configure SystemJS --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
      System.config({
        <span class="hljs-attr">packages</span>: {        
          <span class="hljs-attr">app</span>: {
            <span class="hljs-attr">format</span>: <span class="hljs-string">'register'</span>,
            <span class="hljs-attr">defaultExtension</span>: <span class="hljs-string">'js'</span>
          }
        }
      });
      System.import(<span class="hljs-string">'app/boot'</span>)
            .then(<span class="hljs-literal">null</span>, <span class="hljs-built_in">console</span>.error.bind(<span class="hljs-built_in">console</span>));
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>

  <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>

  <span class="hljs-comment">&lt;!-- 3. Display the application --&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">my-app</span>&gt;</span>Loading...<span class="hljs-tag">&lt;/<span class="hljs-name">my-app</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>

<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p><strong>boot.ts</strong></p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> {bootstrap}    <span class="hljs-keyword">from</span> <span class="hljs-string">'angular2/platform/browser'</span>
<span class="hljs-keyword">import</span> {ROUTER_PROVIDERS} <span class="hljs-keyword">from</span> <span class="hljs-string">'angular2/router'</span>;

<span class="hljs-keyword">import</span> {AppComponent} <span class="hljs-keyword">from</span> <span class="hljs-string">'./app.component'</span>

bootstrap(AppComponent, [
    ROUTER_PROVIDERS
]);
</code></pre>
<p><strong>app.component.ts</strong></p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> {Component} <span class="hljs-keyword">from</span> <span class="hljs-string">'angular2/core'</span>;
<span class="hljs-keyword">import</span> {RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS, LocationStrategy, HashLocationStrategy} <span class="hljs-keyword">from</span> <span class="hljs-string">'angular2/router'</span>;

<span class="hljs-keyword">import</span> {RoutingTestComponent} <span class="hljs-keyword">from</span> <span class="hljs-string">'./routing-test.component'</span>;

<span class="hljs-meta">@Component</span>({
    selector: <span class="hljs-string">'my-app'</span>,
    template: <span class="hljs-string">`
        &lt;h1&gt;Component Router&lt;/h1&gt;
        &lt;a [routerLink]="['RoutingTest']"&gt;Routing Test&lt;/a&gt;
        &lt;router-outlet&gt;&lt;/router-outlet&gt;
        `</span>
})

<span class="hljs-meta">@RouteConfig</span>([
    {path:<span class="hljs-string">'/routing-test'</span>, name: <span class="hljs-string">'RoutingTest'</span>, component: RoutingTestComponent, useAsDefault: <span class="hljs-literal">true</span>},
])

<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> AppComponent { }
</code></pre>
<p><strong>routing-test.component.ts</strong></p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> {Component} <span class="hljs-keyword">from</span> <span class="hljs-string">'angular2/core'</span>;
<span class="hljs-keyword">import</span> {Router} <span class="hljs-keyword">from</span> <span class="hljs-string">'angular2/router'</span>;

<span class="hljs-meta">@Component</span>({
    template: <span class="hljs-string">`
        &lt;h2&gt;Routing Test&lt;/h2&gt;
        &lt;p&gt;Interesting stuff goes here!&lt;/p&gt;
        `</span>
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> RoutingTestComponent { }
</code></pre>
<p>Attempting to run this code produces the error:</p>
<pre><code class="lang-bash">EXCEPTION: Template parse errors:
Can<span class="hljs-string">'t bind to '</span>routerLink<span class="hljs-string">' since it isn'</span>t a known native property (<span class="hljs-string">"
        &lt;h1&gt;Component Router&lt;/h1&gt;
        &lt;a [ERROR -&gt;][routerLink]="</span>[<span class="hljs-string">'RoutingTest'</span>]<span class="hljs-string">"&gt;Routing Test&lt;/a&gt;
        &lt;router-outlet&gt;&lt;/router-outlet&gt;
        "</span>): AppComponent@2:11
</code></pre>
<p>I found a vaguely related issue here; <a target="_blank" href="https://stackoverflow.com/questions/34304115/router-link-directives-broken-after-upgrading-to-angular2-0-0-beta-0">router-link directives broken after upgrading to angular2.0.0-beta.0</a>. However, the “working example” in one of the answers is based on pre-beta code — which may well still work, but I would like to know why the code I have created is not working.</p>
<p>Any pointers would be gratefully received!</p>
<blockquote>
<p><a target="_blank" href="https://stackoverflow.com/users/217408"><strong><em>Günter Zöchbauer</em></strong></a> <strong><em>answered, (220+ points)</em></strong></p>
</blockquote>
<p><strong>&gt;=R</strong>C.5</p>
<p>import the <code>RouterModule</code> See also <a target="_blank" href="https://angular.io/docs/ts/latest/guide/router.html">https://angular.io/docs/ts/latest/guide/router.html</a></p>
<pre><code class="lang-ts"><span class="hljs-meta">@NgModule</span>({ 
  imports: [RouterModule],
  ...
})
</code></pre>
<p><strong>&gt;=R</strong>C.2</p>
<p><strong>app.routes.ts</strong></p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> { provideRouter, RouterConfig } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/router'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> routes: RouterConfig = [
  ...
];

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> APP_ROUTER_PROVIDERS = [provideRouter(routes)];
</code></pre>
<p><strong>main.ts</strong></p>
<pre><code><span class="hljs-keyword">import</span> { bootstrap } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/platform-browser-dynamic'</span>;
<span class="hljs-keyword">import</span> { APP_ROUTER_PROVIDERS } <span class="hljs-keyword">from</span> <span class="hljs-string">'./app.routes'</span>;

bootstrap(AppComponent, [APP_ROUTER_PROVIDERS]);
</code></pre><p><strong>&lt;=RC.1</strong></p>
<p>Your code is missing</p>
<pre><code class="lang-ts"><span class="hljs-meta">@Component</span>({
    ...
    directives: [ROUTER_DIRECTIVES],
    ...)}
</code></pre>
<p>You can’t use directives like <code>routerLink</code> or <code>router-outlet</code> without making them known to your component.</p>
<p>While directive names were changed to be case-sensitive in Angular2, elements still use <code>-</code> in the name like <code>&lt;router-outl</code>et&gt; to be compatible with the web-components spec which requ<code>i</code>re a - in the name of custom elements.</p>
<p><strong>register globally</strong></p>
<p>To make <code>ROUTER_DIRECTIVES</code> globally available, add this provider to <code>bootstrap(...)</code>:</p>
<pre><code>provide(PLATFORM_DIRECTIVES, {<span class="hljs-attr">useValue</span>: [ROUTER_DIRECTIVES], <span class="hljs-attr">multi</span>: <span class="hljs-literal">true</span>})
</code></pre><p>then it’s no longer necessary to add <code>ROUTER_DIRECTIVES</code> to each component.</p>
<p><a target="_blank" href="https://stackoverflow.com/questions/34317044"><strong>Source</strong></a><br><strong><a class="post-section-overview" href="#599b">Top</a></strong></p>
<h3 id="heading-angular-2-dynamic-tabs-with-user-click-chosen-components">Angular 2 dynamic tabs with user-click chosen components</h3>
<blockquote>
<p>143+ points _? 8<em>0,735+ viewed   
</em><a target="_blank" href="https://stackoverflow.com/users/2951897/cuel"><strong>Cuel</strong></a> <strong>asked,</strong>_</p>
</blockquote>
<p>I’m trying to setup a tab system that allows for components to register themselves (with a title). The first tab is like an inbox, there’s plenty of actions/link items to choose from for the users, and each of these clicks should be able to instantiate a new component, on click. The actions / links comes in from JSON.</p>
<p>The instantiated component will then register itself as a new tab.</p>
<p>I’m not sure if this is the ‘best’ approach? Sofar the only guides I’ve seen are for static tabs, which doesn’t help.</p>
<p>So far I’ve only got the tabs service which is bootstrapped in main to persist throughout the app, looks ~something like this.</p>
<pre><code class="lang-ts"><span class="hljs-keyword">export</span> <span class="hljs-keyword">interface</span> ITab { title: <span class="hljs-built_in">string</span>; }

<span class="hljs-meta">@Injectable</span>()
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> TabsService {
    <span class="hljs-keyword">private</span> tabs = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>&lt;ITab&gt;();

    addTab(title: <span class="hljs-built_in">string</span>): ITab {
        <span class="hljs-keyword">let</span> tab: ITab = { title };
        <span class="hljs-built_in">this</span>.tabs.add(tab);
        <span class="hljs-keyword">return</span> tab;
    }

    removeTab(tab: ITab) {
        <span class="hljs-built_in">this</span>.tabs.delete(tab);
    }
}
</code></pre>
<p>Questions:</p>
<p>1) How can I have a dynamic list in the inbox that creates new (different) tabs? I am sort of guessing the DynamicComponentBuilder would be used?</p>
<p>2) How can the components created from the inbox (on click) register themselves as tabs and also be shown? I’m guessing ng-content but I can’t find much info on how to use it</p>
<p>Edit: Try to clarify</p>
<p>Think of the inbox as a mail inbox, items are fetched as JSON and displays several items. Once one of the items is clicked, a new tab is created with that items action ‘type’. The type is then a component</p>
<p>Edit2: Image</p>
<p><a target="_blank" href="http://i.imgur.com/yzfMOXJ.png">http://i.imgur.com/yzfMOXJ.png</a></p>
<blockquote>
<p><a target="_blank" href="https://stackoverflow.com/users/217408"><strong><em>Günter Zöchbauer</em></strong></a> <strong><em>answered, (190+ points)</em></strong></p>
</blockquote>
<p><strong>update</strong></p>
<p><a target="_blank" href="https://stackblitz.com/edit/angular-ygz3jg"><strong>Angular 5 StackBlitz example</strong></a></p>
<p><strong>update</strong></p>
<p><code>ngComponentOutlet</code> was added to 4.0.0-beta.3</p>
<p><strong>update</strong></p>
<p>There is a <code>NgComponentOutlet</code> work in progress that does something similar <a target="_blank" href="https://github.com/angular/angular/pull/11235">https://github.com/angular/angular/pull/11235</a></p>
<p><strong>RC.7</strong></p>
<p><a target="_blank" href="http://plnkr.co/edit/UGzoPTCHlXKWrn4p8gd1?p=preview"><strong>Plunker example RC.7</strong></a></p>
<pre><code class="lang-ts"><span class="hljs-comment">// Helper component to add dynamic components</span>
<span class="hljs-meta">@Component</span>({
  selector: <span class="hljs-string">'dcl-wrapper'</span>,
  template: <span class="hljs-string">`&lt;div #target&gt;&lt;/div&gt;`</span>
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> DclWrapper {
  <span class="hljs-meta">@ViewChild</span>(<span class="hljs-string">'target'</span>, {read: ViewContainerRef}) target: ViewContainerRef;
  <span class="hljs-meta">@Input</span>() <span class="hljs-keyword">type</span>: Type&lt;Component&gt;;
  cmpRef: ComponentRef&lt;Component&gt;;
  <span class="hljs-keyword">private</span> isViewInitialized:<span class="hljs-built_in">boolean</span> = <span class="hljs-literal">false</span>;

  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> componentFactoryResolver: ComponentFactoryResolver, <span class="hljs-keyword">private</span> compiler: Compiler</span>) {}

  updateComponent() {
    <span class="hljs-keyword">if</span>(!<span class="hljs-built_in">this</span>.isViewInitialized) {
      <span class="hljs-keyword">return</span>;
    }
    <span class="hljs-keyword">if</span>(<span class="hljs-built_in">this</span>.cmpRef) {
      <span class="hljs-comment">// when the `type` input changes we destroy a previously </span>
      <span class="hljs-comment">// created component before creating the new one</span>
      <span class="hljs-built_in">this</span>.cmpRef.destroy();
    }

    <span class="hljs-keyword">let</span> factory = <span class="hljs-built_in">this</span>.componentFactoryResolver.resolveComponentFactory(<span class="hljs-built_in">this</span>.type);
    <span class="hljs-built_in">this</span>.cmpRef = <span class="hljs-built_in">this</span>.target.createComponent(factory)
    <span class="hljs-comment">// to access the created instance use</span>
    <span class="hljs-comment">// this.compRef.instance.someProperty = 'someValue';</span>
    <span class="hljs-comment">// this.compRef.instance.someOutput.subscribe(val =&gt; doSomething());</span>
  }

  ngOnChanges() {
    <span class="hljs-built_in">this</span>.updateComponent();
  }

  ngAfterViewInit() {
    <span class="hljs-built_in">this</span>.isViewInitialized = <span class="hljs-literal">true</span>;
    <span class="hljs-built_in">this</span>.updateComponent();  
  }

  ngOnDestroy() {
    <span class="hljs-keyword">if</span>(<span class="hljs-built_in">this</span>.cmpRef) {
      <span class="hljs-built_in">this</span>.cmpRef.destroy();
    }    
  }
}
</code></pre>
<p>Usage example</p>
<pre><code class="lang-ts"><span class="hljs-comment">// Use dcl-wrapper component</span>
<span class="hljs-meta">@Component</span>({
  selector: <span class="hljs-string">'my-tabs'</span>,
  template: <span class="hljs-string">`
  &lt;h2&gt;Tabs&lt;/h2&gt;
  &lt;div *ngFor="let tab of tabs"&gt;
    &lt;dcl-wrapper [type]="tab"&gt;&lt;/dcl-wrapper&gt;
  &lt;/div&gt;
`</span>
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> Tabs {
  <span class="hljs-meta">@Input</span>() tabs;
}

<span class="hljs-meta">@Component</span>({
  selector: <span class="hljs-string">'my-app'</span>,
  template: <span class="hljs-string">`
  &lt;h2&gt;Hello {{name}}&lt;/h2&gt;
  &lt;my-tabs [tabs]="types"&gt;&lt;/my-tabs&gt;
`</span>
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> App {
  <span class="hljs-comment">// The list of components to create tabs from</span>
  types = [C3, C1, C2, C3, C3, C1, C1];
}

<span class="hljs-meta">@NgModule</span>({
  imports: [ BrowserModule ],
  declarations: [ App, DclWrapper, Tabs, C1, C2, C3],
  entryComponents: [C1, C2, C3],
  bootstrap: [ App ]
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> AppModule {}
</code></pre>
<p>See also <a target="_blank" href="https://angular.io/docs/ts/latest/cookbook/dynamic-component-loader.html">angular.io DYNAMIC COMPONENT LOADER</a></p>
<p><strong>older versions</strong> <strong>xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</strong></p>
<p>This changed again in Angular2 RC.5</p>
<p>I will update the example below but it’s the last day before vacation.</p>
<p>This <a target="_blank" href="http://plnkr.co/edit/3dzkMVXe4AGSRhk11TXG?p=preview">Plunker example</a> demonstrates how to dynamically create components in RC.5</p>
<p><strong>Update — use <a target="_blank" href="https://angular.io/docs/ts/latest/api/core/index/ViewContainerRef-class.html">ViewContainerRef</a>.createComponent()</strong></p>
<p>Because <code>DynamicComponentLoader</code> is deprecated, the approach needs to be update again.</p>
<pre><code class="lang-ts"><span class="hljs-meta">@Component</span>({
  selector: <span class="hljs-string">'dcl-wrapper'</span>,
  template: <span class="hljs-string">`&lt;div #target&gt;&lt;/div&gt;`</span>
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> DclWrapper {
  <span class="hljs-meta">@ViewChild</span>(<span class="hljs-string">'target'</span>, {read: ViewContainerRef}) target;
  <span class="hljs-meta">@Input</span>() <span class="hljs-keyword">type</span>;
  cmpRef:ComponentRef;
  <span class="hljs-keyword">private</span> isViewInitialized:<span class="hljs-built_in">boolean</span> = <span class="hljs-literal">false</span>;

  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> resolver: ComponentResolver</span>) {}

  updateComponent() {
    <span class="hljs-keyword">if</span>(!<span class="hljs-built_in">this</span>.isViewInitialized) {
      <span class="hljs-keyword">return</span>;
    }
    <span class="hljs-keyword">if</span>(<span class="hljs-built_in">this</span>.cmpRef) {
      <span class="hljs-built_in">this</span>.cmpRef.destroy();
    }
   <span class="hljs-built_in">this</span>.resolver.resolveComponent(<span class="hljs-built_in">this</span>.type).then(<span class="hljs-function">(<span class="hljs-params">factory:ComponentFactory&lt;<span class="hljs-built_in">any</span>&gt;</span>) =&gt;</span> {
      <span class="hljs-built_in">this</span>.cmpRef = <span class="hljs-built_in">this</span>.target.createComponent(factory)
      <span class="hljs-comment">// to access the created instance use</span>
      <span class="hljs-comment">// this.compRef.instance.someProperty = 'someValue';</span>
      <span class="hljs-comment">// this.compRef.instance.someOutput.subscribe(val =&gt; doSomething());</span>
    });
  }

  ngOnChanges() {
    <span class="hljs-built_in">this</span>.updateComponent();
  }

  ngAfterViewInit() {
    <span class="hljs-built_in">this</span>.isViewInitialized = <span class="hljs-literal">true</span>;
    <span class="hljs-built_in">this</span>.updateComponent();  
  }
  ngOnDestroy() {
    <span class="hljs-keyword">if</span>(<span class="hljs-built_in">this</span>.cmpRef) {
      <span class="hljs-built_in">this</span>.cmpRef.destroy();
    }    
  }
}
</code></pre>
<p><a target="_blank" href="http://plnkr.co/edit/GJTLrnQdRDBvZenX59PZ?p=preview"><strong>Plunker example RC.4</strong></a><br><a target="_blank" href="https://plnkr.co/edit/PpgMvS?p=preview"><strong>Plunker example beta.17</strong></a></p>
<p><strong>Update — use loadNextToLocation</strong></p>
<pre><code class="lang-ts"><span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> DclWrapper {
  <span class="hljs-meta">@ViewChild</span>(<span class="hljs-string">'target'</span>, {read: ViewContainerRef}) target;
  <span class="hljs-meta">@Input</span>() <span class="hljs-keyword">type</span>;
  cmpRef:ComponentRef;
  <span class="hljs-keyword">private</span> isViewInitialized:<span class="hljs-built_in">boolean</span> = <span class="hljs-literal">false</span>;

  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> dcl:DynamicComponentLoader</span>) {}

  updateComponent() {
    <span class="hljs-comment">// should be executed every time `type` changes but not before `ngAfterViewInit()` was called </span>
    <span class="hljs-comment">// to have `target` initialized</span>
    <span class="hljs-keyword">if</span>(!<span class="hljs-built_in">this</span>.isViewInitialized) {
      <span class="hljs-keyword">return</span>;
    }
    <span class="hljs-keyword">if</span>(<span class="hljs-built_in">this</span>.cmpRef) {
      <span class="hljs-built_in">this</span>.cmpRef.destroy();
    }
    <span class="hljs-built_in">this</span>.dcl.loadNextToLocation(<span class="hljs-built_in">this</span>.type, <span class="hljs-built_in">this</span>.target).then(<span class="hljs-function">(<span class="hljs-params">cmpRef</span>) =&gt;</span> {
      <span class="hljs-built_in">this</span>.cmpRef = cmpRef;
    });
  }

  ngOnChanges() {
    <span class="hljs-built_in">this</span>.updateComponent();
  }

  ngAfterViewInit() {
    <span class="hljs-built_in">this</span>.isViewInitialized = <span class="hljs-literal">true</span>;
    <span class="hljs-built_in">this</span>.updateComponent();  
  }

  ngOnDestroy() {
    <span class="hljs-keyword">if</span>(<span class="hljs-built_in">this</span>.cmpRef) {
      <span class="hljs-built_in">this</span>.cmpRef.destroy();
    }    
  }
}
</code></pre>
<p><a target="_blank" href="https://plnkr.co/edit/kc2Bgg?p=preview"><strong>Plunker example beta.17</strong></a></p>
<p><strong>original</strong></p>
<p>Not entirely sure from your question what your requirements are but I think this should do what you want.</p>
<p>The <code>Tabs</code> component gets an array of types passed and it creates "tabs" for each item in the array.</p>
<pre><code class="lang-ts"><span class="hljs-meta">@Component</span>({
  selector: <span class="hljs-string">'dcl-wrapper'</span>,
  template: <span class="hljs-string">`&lt;div #target&gt;&lt;/div&gt;`</span>
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> DclWrapper {
  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> elRef:ElementRef, <span class="hljs-keyword">private</span> dcl:DynamicComponentLoader</span>) {}
  <span class="hljs-meta">@Input</span>() <span class="hljs-keyword">type</span>;

  ngOnChanges() {
    <span class="hljs-keyword">if</span>(<span class="hljs-built_in">this</span>.cmpRef) {
      <span class="hljs-built_in">this</span>.cmpRef.dispose();
    }
    <span class="hljs-built_in">this</span>.dcl.loadIntoLocation(<span class="hljs-built_in">this</span>.type, <span class="hljs-built_in">this</span>.elRef, <span class="hljs-string">'target'</span>).then(<span class="hljs-function">(<span class="hljs-params">cmpRef</span>) =&gt;</span> {
      <span class="hljs-built_in">this</span>.cmpRef = cmpRef;
    });
  }
}

<span class="hljs-meta">@Component</span>({
  selector: <span class="hljs-string">'c1'</span>,
  template: <span class="hljs-string">`&lt;h2&gt;c1&lt;/h2&gt;`</span>

})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> C1 {
}

<span class="hljs-meta">@Component</span>({
  selector: <span class="hljs-string">'c2'</span>,
  template: <span class="hljs-string">`&lt;h2&gt;c2&lt;/h2&gt;`</span>
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> C2 {
}
<span class="hljs-meta">@Component</span>({
  selector: <span class="hljs-string">'c3'</span>,
  template: <span class="hljs-string">`&lt;h2&gt;c3&lt;/h2&gt;`</span>

})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> C3 {
}

<span class="hljs-meta">@Component</span>({
  selector: <span class="hljs-string">'my-tabs'</span>,
  directives: [DclWrapper],
  template: <span class="hljs-string">`
  &lt;h2&gt;Tabs&lt;/h2&gt;
  &lt;div *ngFor="let tab of tabs"&gt;
    &lt;dcl-wrapper [type]="tab"&gt;&lt;/dcl-wrapper&gt;
  &lt;/div&gt;
`</span>
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> Tabs {
  <span class="hljs-meta">@Input</span>() tabs;
}

<span class="hljs-meta">@Component</span>({
  selector: <span class="hljs-string">'my-app'</span>,
  directives: [Tabs]
  template: <span class="hljs-string">`
  &lt;h2&gt;Hello {{name}}&lt;/h2&gt;
  &lt;my-tabs [tabs]="types"&gt;&lt;/my-tabs&gt;
`</span>
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> App {
  types = [C3, C1, C2, C3, C3, C1, C1];
}
</code></pre>
<p><a target="_blank" href="https://plnkr.co/edit/kc2Bgg?p=preview"><strong>Plunker example beta.15</strong></a> (not based on your Plunker)</p>
<p>There is also a way to pass data along that can be passed to the dynamically created component like (<code>someData</code> would need to be passed like <code>type</code>)</p>
<pre><code class="lang-ts"><span class="hljs-built_in">this</span>.dcl.loadIntoLocation(<span class="hljs-built_in">this</span>.type, <span class="hljs-built_in">this</span>.elRef, <span class="hljs-string">'target'</span>).then(<span class="hljs-function">(<span class="hljs-params">cmpRef</span>) =&gt;</span> {
  cmpRef.instance.someProperty = someData;
  <span class="hljs-built_in">this</span>.cmpRef = cmpRef;
});
</code></pre>
<p>There is also some support to use dependency injection with shared services.</p>
<p>For more details see <a target="_blank" href="https://angular.io/docs/ts/latest/cookbook/dynamic-component-loader.html">https://angular.io/docs/ts/latest/cookbook/dynamic-component-loader.html</a></p>
<p><a target="_blank" href="https://stackoverflow.com/questions/36325212"><strong>Source</strong></a><br><strong><a class="post-section-overview" href="#599b">Top</a></strong></p>
<h3 id="heading-delegation-eventemitter-or-observable-in-angular">Delegation: EventEmitter or Observable in Angular</h3>
<blockquote>
<p>141+ points _? 7<em>8,505+ viewed   
</em><a target="_blank" href="https://stackoverflow.com/users/1066899/the-critic"><strong>the_critic</strong></a> <strong>asked,</strong>_</p>
</blockquote>
<p>I am trying to implement something like a delegation pattern in Angular. When the user clicks on a <code>nav-item</code>, I would like to call a function which then emits an event which should in turn be handled by some other component listening for the event.</p>
<p>Here is the scenario: I have a <code>Navigation</code> component:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> {Component, Output, EventEmitter} <span class="hljs-keyword">from</span> <span class="hljs-string">'angular2/core'</span>;

<span class="hljs-meta">@Component</span>({
    <span class="hljs-comment">// other properties left out for brevity</span>
    events : [<span class="hljs-string">'navchange'</span>], 
    template:<span class="hljs-string">`
      &lt;div class="nav-item" (click)="selectedNavItem(1)"&gt;&lt;/div&gt;
    `</span>
})

<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> Navigation {

    <span class="hljs-meta">@Output</span>() navchange: EventEmitter&lt;<span class="hljs-built_in">number</span>&gt; = <span class="hljs-keyword">new</span> EventEmitter();

    selectedNavItem(item: <span class="hljs-built_in">number</span>) {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'selected nav item '</span> + item);
        <span class="hljs-built_in">this</span>.navchange.emit(item)
    }

}
</code></pre>
<p>Here is the observing component:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> ObservingComponent {

  <span class="hljs-comment">// How do I observe the event ? </span>
  <span class="hljs-comment">// &lt;----------Observe/Register Event ?--------&gt;</span>

  <span class="hljs-keyword">public</span> selectedNavItem(item: <span class="hljs-built_in">number</span>) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'item index changed!'</span>);
  }

}
</code></pre>
<p>The key question is, how do I make the observing component observe the event in question ?</p>
<blockquote>
<p><a target="_blank" href="https://stackoverflow.com/users/215945"><strong><em>Mark Rajcok</em></strong></a> <strong><em>answered, (306+ points)</em></strong></p>
</blockquote>
<p><strong>Update 2016–06–27:</strong> instead of using Observables, use either</p>
<ul>
<li>a BehaviorSubject, as recommended by @Abdulrahman in a comment, or</li>
<li>a ReplaySubject, as recommended by @Jason Goemaat in a comment</li>
</ul>
<p>A <a target="_blank" href="http://reactivex.io/rxjs/manual/overview.html#subject">Subject</a> is both an Observable (so we can <code>subscribe()</code> to it) and an Observer (so we can call <code>next()</code> on it to emit a new value). We exploit this feature. A Subject allows values to be multicast to many Observers. We don't exploit this feature (we only have one Observer).</p>
<p><a target="_blank" href="http://reactivex.io/rxjs/manual/overview.html#behaviorsubject">BehaviorSubject</a> is a variant of Subject. It has the notion of “the current value”. We exploit this: whenever we create an ObservingComponent, it gets the current navigation item value from the BehaviorSubject automatically.</p>
<p>The code below and the <a target="_blank" href="http://plnkr.co/edit/XqwwUM44NQEpxQVFFxNW?p=preview">plunker</a> use BehaviorSubject.</p>
<p><a target="_blank" href="http://reactivex.io/rxjs/manual/overview.html#replaysubject">ReplaySubject</a> is another variant of Subject. If you want to wait until a value is actually produced, use <code>ReplaySubject(1)</code>. Whereas a BehaviorSubject requires an initial value (which will be provided immediately), ReplaySubject does not. ReplaySubject will always provide the most recent value, but since it does not have a required initial value, the service can do some async operation before returning it's first value. It will still fire immediately on subsequent calls with the most recent value. If you just want one value, use <code>first()</code> on the subscription. You do not have to unsubscribe if you use <code>first()</code>.</p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> {Injectable}      <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>
<span class="hljs-keyword">import</span> {BehaviorSubject} <span class="hljs-keyword">from</span> <span class="hljs-string">'rxjs/BehaviorSubject'</span>;

<span class="hljs-meta">@Injectable</span>()
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> NavService {
  <span class="hljs-comment">// Observable navItem source</span>
  <span class="hljs-keyword">private</span> _navItemSource = <span class="hljs-keyword">new</span> BehaviorSubject&lt;<span class="hljs-built_in">number</span>&gt;(<span class="hljs-number">0</span>);
  <span class="hljs-comment">// Observable navItem stream</span>
  navItem$ = <span class="hljs-built_in">this</span>._navItemSource.asObservable();
  <span class="hljs-comment">// service command</span>
  changeNav(<span class="hljs-built_in">number</span>) {
    <span class="hljs-built_in">this</span>._navItemSource.next(<span class="hljs-built_in">number</span>);
  }
}

<span class="hljs-keyword">import</span> {Component}    <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;
<span class="hljs-keyword">import</span> {NavService}   <span class="hljs-keyword">from</span> <span class="hljs-string">'./nav.service'</span>;
<span class="hljs-keyword">import</span> {Subscription} <span class="hljs-keyword">from</span> <span class="hljs-string">'rxjs/Subscription'</span>;

<span class="hljs-meta">@Component</span>({
  selector: <span class="hljs-string">'obs-comp'</span>,
  template: <span class="hljs-string">`obs component, item: {{item}}`</span>
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> ObservingComponent {
  item: <span class="hljs-built_in">number</span>;
  subscription:Subscription;
  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> _navService:NavService</span>) {}
  ngOnInit() {
    <span class="hljs-built_in">this</span>.subscription = <span class="hljs-built_in">this</span>._navService.navItem$
       .subscribe(<span class="hljs-function"><span class="hljs-params">item</span> =&gt;</span> <span class="hljs-built_in">this</span>.item = item)
  }
  ngOnDestroy() {
    <span class="hljs-comment">// prevent memory leak when component is destroyed</span>
    <span class="hljs-built_in">this</span>.subscription.unsubscribe();
  }
}

<span class="hljs-meta">@Component</span>({
  selector: <span class="hljs-string">'my-nav'</span>,
  template:<span class="hljs-string">`
    &lt;div class="nav-item" (click)="selectedNavItem(1)"&gt;nav 1 (click me)&lt;/div&gt;
    &lt;div class="nav-item" (click)="selectedNavItem(2)"&gt;nav 2 (click me)&lt;/div&gt;`</span>
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> Navigation {
  item = <span class="hljs-number">1</span>;
  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> _navService:NavService</span>) {}
  selectedNavItem(item: <span class="hljs-built_in">number</span>) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'selected nav item '</span> + item);
    <span class="hljs-built_in">this</span>._navService.changeNav(item);
  }
}
</code></pre>
<p><a target="_blank" href="http://plnkr.co/edit/XqwwUM44NQEpxQVFFxNW?p=preview">Plunker</a></p>
<p><strong>Original answer that uses an Observable:</strong> (it requires more code and logic than using a BehaviorSubject, so I don’t recommend it, but it may be instructive)</p>
<p>So, here’s an implementation that uses an Observable <a target="_blank" href="https://stackoverflow.com/a/34402436/215945">instead of an EventEmitter</a>. Unlike my EventEmitter implementation, this implementation also stores the currently selected <code>navItem</code> in the service, so that when an observing component is created, it can retrieve the current value via API call <code>navItem()</code>, and then be notified of changes via the <code>navChange$</code> Observable.</p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> {Observable} <span class="hljs-keyword">from</span> <span class="hljs-string">'rxjs/Observable'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'rxjs/add/operator/share'</span>;
<span class="hljs-keyword">import</span> {Observer} <span class="hljs-keyword">from</span> <span class="hljs-string">'rxjs/Observer'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> NavService {
  <span class="hljs-keyword">private</span> _navItem = <span class="hljs-number">0</span>;
  navChange$: Observable&lt;<span class="hljs-built_in">number</span>&gt;;
  <span class="hljs-keyword">private</span> _observer: Observer;
  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"></span>) {
    <span class="hljs-built_in">this</span>.navChange$ = <span class="hljs-keyword">new</span> Observable(<span class="hljs-function"><span class="hljs-params">observer</span> =&gt;</span>
      <span class="hljs-built_in">this</span>._observer = observer).share();
    <span class="hljs-comment">// share() allows multiple subscribers</span>
  }
  changeNav(<span class="hljs-built_in">number</span>) {
    <span class="hljs-built_in">this</span>._navItem = <span class="hljs-built_in">number</span>;
    <span class="hljs-built_in">this</span>._observer.next(<span class="hljs-built_in">number</span>);
  }
  navItem() {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>._navItem;
  }
}

<span class="hljs-meta">@Component</span>({
  selector: <span class="hljs-string">'obs-comp'</span>,
  template: <span class="hljs-string">`obs component, item: {{item}}`</span>
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> ObservingComponent {
  item: <span class="hljs-built_in">number</span>;
  subscription: <span class="hljs-built_in">any</span>;
  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> _navService:NavService</span>) {}
  ngOnInit() {
    <span class="hljs-built_in">this</span>.item = <span class="hljs-built_in">this</span>._navService.navItem();
    <span class="hljs-built_in">this</span>.subscription = <span class="hljs-built_in">this</span>._navService.navChange$.subscribe(
      <span class="hljs-function"><span class="hljs-params">item</span> =&gt;</span> <span class="hljs-built_in">this</span>.selectedNavItem(item));
  }
  selectedNavItem(item: <span class="hljs-built_in">number</span>) {
    <span class="hljs-built_in">this</span>.item = item;
  }
  ngOnDestroy() {
    <span class="hljs-built_in">this</span>.subscription.unsubscribe();
  }
}

<span class="hljs-meta">@Component</span>({
  selector: <span class="hljs-string">'my-nav'</span>,
  template:<span class="hljs-string">`
    &lt;div class="nav-item" (click)="selectedNavItem(1)"&gt;nav 1 (click me)&lt;/div&gt;
    &lt;div class="nav-item" (click)="selectedNavItem(2)"&gt;nav 2 (click me)&lt;/div&gt;
  `</span>,
})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> Navigation {
  item:<span class="hljs-built_in">number</span>;
  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> _navService:NavService</span>) {}
  selectedNavItem(item: <span class="hljs-built_in">number</span>) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'selected nav item '</span> + item);
    <span class="hljs-built_in">this</span>._navService.changeNav(item);
  }
}
</code></pre>
<p><a target="_blank" href="http://plnkr.co/edit/vL76b0UjrAav3Ao7kF4W?p=preview">Plunker</a></p>
<p>See also the <a target="_blank" href="https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service">Component Interaction Cookbook example</a>, which uses a <code>Subject</code> in addition to observables. Although the example is "parent and children communication," the same technique is applicable for unrelated components.</p>
<p><a target="_blank" href="https://stackoverflow.com/questions/34376854"><strong>Source</strong></a><br><strong><a class="post-section-overview" href="#599b">Top</a></strong></p>
<h3 id="heading-how-to-add-bootstrap-to-an-angular-cli-project">How to add bootstrap to an angular-cli project</h3>
<blockquote>
<p>140+ points _? 1<em>66,741+ viewed   
</em><a target="_blank" href="https://stackoverflow.com/users/811865/jerome"><strong>Jerome</strong></a> <strong>asked,</strong>_</p>
</blockquote>
<p>We want to use bootstrap 4 (4.0.0-alpha.2) in our app generated with angular-cli 1.0.0-beta.5 (w/ node v6.1.0).</p>
<p>After getting bootstrap and its dependencies with npm, our first approach consisted in adding them in <code>angular-cli-build.js</code>:</p>
<pre><code class="lang-js"><span class="hljs-string">'bootstrap/dist/**/*.min.+(js|css)'</span>,  
  <span class="hljs-string">'jquery/dist/jquery.min.+(js|map)'</span>,  
  <span class="hljs-string">'tether/dist/**/*.min.+(js|css)'</span>,
</code></pre>
<p>and import them in our <code>index.html</code></p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"vendor/jquery/dist/jquery.min.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"vendor/tether/dist/js/tether.min.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text/css"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"vendor/bootstrap/dist/css/bootstrap.min.css"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"vendor/bootstrap/dist/js/bootstrap.min.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<p>This worked fine with <code>ng serve</code> but as soon as we produced a build with <code>-prod</code> flag all these dependencies disappeared from <code>dist/vendor</code> (surprise !).</p>
<p><strong>How we are intended to handle such scenario (i.e. loading bootstrap scripts) in a project generated with angular-cli ?</strong></p>
<p>We had the following thoughts but we don’t really know which way to go…</p>
<ul>
<li>use a CDN ? but we would rather serve these files to guarantee that they will be available</li>
<li>copy dependencies to <code>dist/vendor</code> after our <code>ng build -prod</code> ? But that seems like something angular-cli should provide since it 'takes care' of the build part ?</li>
<li>adding jquery, bootstrap and tether in src/system-config.ts and somehow pull them into our bundle in main.ts ? But that seemed wrong considering that we are not going to explicitly use them in our application’s code (unlike moment.js or something like lodash, for example)</li>
</ul>
<blockquote>
<p><a target="_blank" href="https://stackoverflow.com/users/1417742"><strong><em>pd farhad</em></strong></a> <strong><em>answered, (202+ points)</em></strong></p>
</blockquote>
<p><strong>IMPORTANT UPDATE: ng2-bootstrap is now replaced by <a target="_blank" href="https://github.com/valor-software/ngx-bootstrap">ngx-bootstrap</a> </strong></p>
<p>ngx-bootstrap supports both angular 3 and 4.</p>
<p><strong>Update :</strong> <code>**1.0.0-beta.11-webpack**</code> <strong>or above versions</strong></p>
<p>First of all check your angular-cli version with the following command in the terminal: <code>ng -v</code></p>
<p>If your angular-cli version is greater than <code>1.0.0-beta.11-webpack</code> then you should follow these steps:</p>
<ol>
<li>install <strong>ngx-bootstrap</strong> and <strong>bootstrap:</strong><br><code>npm install ngx-bootstrap bootstrap --save</code></li>
</ol>
<p>This line installs bootstrap 3 nowadays, but can install bootstrap 4 in future. Keep in mind ngx-bootstrap supports both versions.</p>
<ol>
<li>open <strong>src/app/app.module.ts</strong> and add<br><code>import { AlertModule } from 'ngx-bootstrap'; ... @NgModule({ ... imports: [AlertModule.forRoot(), ... ], ... })</code></li>
<li>open <strong>angular-cli.json</strong> and insert a new entry into the styles array<br><code>"styles": [ "styles.css", "../node_modules/bootstrap/dist/css/bootstrap.min.css" ],</code></li>
<li>open <strong>src/app/app.component.html</strong> and add<br><code>&lt;alert type="success"&gt;hello&amp;l</code>t;/alert&gt;</li>
</ol>
<p><strong>1.0.0-beta.10 or below versions:</strong></p>
<p>And, if your angular-cli version is 1.0.0-beta.10 or below versions then you can use below steps.</p>
<p>First go to the project directory and type</p>
<pre><code>npm install ngx-bootstrap --save
</code></pre><p>then open your <strong>angular-cli-build.js</strong> and add this line</p>
<pre><code class="lang-js">vendorNpmFiles: [
   ..................
   <span class="hljs-string">'ngx-bootstrap/**/*.js'</span>,
    ....................
  ]
</code></pre>
<p>now open your <strong>src/system-config.ts</strong>, write</p>
<pre><code class="lang-ts"><span class="hljs-keyword">const</span> map:<span class="hljs-built_in">any</span> = {
     ..................
   <span class="hljs-string">'ngx-bootstrap'</span>: <span class="hljs-string">'vendor/ngx-bootstrap'</span>,
    ....................
}
</code></pre>
<p>and</p>
<pre><code class="lang-ts"><span class="hljs-keyword">const</span> packages: <span class="hljs-built_in">any</span> = {
  <span class="hljs-string">'ngx-bootstrap'</span>: {
    format: <span class="hljs-string">'cjs'</span>,
    defaultExtension: <span class="hljs-string">'js'</span>,
    main: <span class="hljs-string">'ngx-bootstrap.js'</span>
  }
};
</code></pre>
<p><a target="_blank" href="https://stackoverflow.com/questions/37649164"><strong>Source</strong></a><br><strong><a class="post-section-overview" href="#599b">Top</a></strong></p>
<h3 id="heading-access-key-and-value-of-object-using-ngfor">access key and value of object using *ngFor</h3>
<blockquote>
<p>136+ points _? 1<em>39,816+ viewed   
</em><a target="_blank" href="https://stackoverflow.com/users/5043867/pardeep-jain"><strong>Pardeep Jain</strong></a> <strong>asked,</strong>_</p>
</blockquote>
<p>Bit confused about how to get <code>Key and Value</code> of object in angular2 while usng *ngFor for iteration over object. i know in angular 1.x there is syntax like</p>
<pre><code class="lang-ts">ng-repeat=<span class="hljs-string">"(key, value) in demo"</span>
</code></pre>
<p>but in angular2 i don’t know i tired the same but did’t get successful. i have tried the below code but did’t run please tell me where i am doing wrong.</p>
<pre><code class="lang-ts">&lt;ul&gt;
  &lt;li *ngFor=<span class="hljs-string">'#key of demo'</span>&gt;{{key}}&lt;/li&gt;
&lt;/ul&gt;

demo = {
    <span class="hljs-string">'key1'</span>: [{<span class="hljs-string">'key11'</span>:<span class="hljs-string">'value11'</span>}, {<span class="hljs-string">'key12'</span>:<span class="hljs-string">'value12'</span>}],
    <span class="hljs-string">'key2'</span>: [{<span class="hljs-string">'key21'</span>:<span class="hljs-string">'value21'</span>}, {<span class="hljs-string">'key22'</span>:<span class="hljs-string">'value22'</span>}],
  }
</code></pre>
<p>here is plnkr where i have tried the same : <a target="_blank" href="http://plnkr.co/edit/mIj619FncOpfdwrR0KeG?p=preview">http://plnkr.co/edit/mIj619FncOpfdwrR0KeG?p=preview</a></p>
<p>I want to get <code>key1</code> and <code>key2</code> dynamically using *ngFor. How to get it? i searched a lot found idea of using pipe but how to use i dont know. is there any inbuild pipe for doing same in angular2 ?</p>
<blockquote>
<p><a target="_blank" href="https://stackoverflow.com/users/1873365"><strong><em>Thierry Templier</em></strong></a> <strong><em>answered, (134+ points)</em></strong></p>
</blockquote>
<p>You could create a custom pipe to return the list of key for each element. Something like that:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> { PipeTransform, Pipe } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/core'</span>;

<span class="hljs-meta">@Pipe</span>({name: <span class="hljs-string">'keys'</span>})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> KeysPipe <span class="hljs-keyword">implements</span> PipeTransform {
  transform(value, args:<span class="hljs-built_in">string</span>[]) : <span class="hljs-built_in">any</span> {
    <span class="hljs-keyword">let</span> keys = [];
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> key <span class="hljs-keyword">in</span> value) {
      keys.push(key);
    }
    <span class="hljs-keyword">return</span> keys;
  }
}
</code></pre>
<p>and use it like that:</p>
<pre><code class="lang-ts">&lt;tr *ngFor=<span class="hljs-string">"let c of content"</span>&gt;           
  &lt;td *ngFor=<span class="hljs-string">"let key of c | keys"</span>&gt;{{key}}: {{c[key]}}&lt;/td&gt;
&lt;/tr&gt;
</code></pre>
<p><strong>Edit</strong></p>
<p>You could also return an entry containing both key and value:</p>
<pre><code class="lang-ts"><span class="hljs-meta">@Pipe</span>({name: <span class="hljs-string">'keys'</span>})
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> KeysPipe <span class="hljs-keyword">implements</span> PipeTransform {
  transform(value, args:<span class="hljs-built_in">string</span>[]) : <span class="hljs-built_in">any</span> {
    <span class="hljs-keyword">let</span> keys = [];
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> key <span class="hljs-keyword">in</span> value) {
      keys.push({key: key, value: value[key]});
    }
    <span class="hljs-keyword">return</span> keys;
  }
}
</code></pre>
<p>and use it like that:</p>
<pre><code class="lang-ts">&lt;span *ngFor=<span class="hljs-string">"let entry of content | keys"</span>&gt;           
  Key: {{entry.key}}, value: {{entry.value}}
&lt;/span&gt;
</code></pre>
<p><a target="_blank" href="https://stackoverflow.com/questions/35534959"><strong>Source</strong></a><br><strong><a class="post-section-overview" href="#599b">Top</a></strong></p>
<h3 id="heading-angular-exception-cant-bind-to-ngfor-since-it-isnt-a-known-native-property">Angular exception: Can’t bind to ‘ngFor’ since it isn’t a known native property</h3>
<blockquote>
<p>134+ points _? 6<em>3,054+ viewed   
</em><a target="_blank" href="https://stackoverflow.com/users/215945/mark-rajcok"><strong>Mark Rajcok</strong></a> <strong>asked,</strong>_</p>
</blockquote>
<p>What am I doing wrong?</p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> {bootstrap, Component} <span class="hljs-keyword">from</span> <span class="hljs-string">'angular2/angular2'</span>

<span class="hljs-meta">@Component</span>({
  selector: <span class="hljs-string">'conf-talks'</span>,
  template: <span class="hljs-string">`&lt;div *ngFor="talk of talks"&gt;
     {{talk.title}} by {{talk.speaker}}
     &lt;p&gt;{{talk.description}}
   &lt;/div&gt;`</span>
})
<span class="hljs-keyword">class</span> ConfTalks {
  talks = [ {title: <span class="hljs-string">'t1'</span>, speaker: <span class="hljs-string">'Brian'</span>, description: <span class="hljs-string">'talk 1'</span>},
            {title: <span class="hljs-string">'t2'</span>, speaker: <span class="hljs-string">'Julie'</span>, description: <span class="hljs-string">'talk 2'</span>}];
}
<span class="hljs-meta">@Component</span>({
  selector: <span class="hljs-string">'my-app'</span>,
  directives: [ConfTalks],
  template: <span class="hljs-string">'&lt;conf-talks&gt;&lt;/conf-talks&gt;'</span>
})
<span class="hljs-keyword">class</span> App {}
bootstrap(App, [])
</code></pre>
<p>The error is</p>
<pre><code class="lang-bash">EXCEPTION: Template parse errors:
Can<span class="hljs-string">'t bind to '</span>ngFor<span class="hljs-string">' since it isn'</span>t a known native property
(<span class="hljs-string">"&lt;div [ERROR -&gt;]*ngFor="</span>talk of talks<span class="hljs-string">"&gt;</span>
</code></pre>
<blockquote>
<p><a target="_blank" href="https://stackoverflow.com/users/215945"><strong><em>Mark Rajcok</em></strong></a> <strong><em>answered, (325+ points)</em></strong></p>
</blockquote>
<p>I missed <code>let</code> in front of <code>talk</code>:</p>
<pre><code class="lang-ts">&lt;div *ngFor=<span class="hljs-string">"let talk of talks"</span>&gt;
</code></pre>
<p>Note that <a target="_blank" href="https://github.com/angular/angular/blob/master/CHANGELOG.md#200-beta17-2016-04-28">as of beta.17</a> usage of <code>#...</code> to declare local variables inside of structural directives like NgFor is deprecated. Use <code>let</code> instead.<br><code>&lt;div *ngFor="#talk of talk</code>s"&gt; now be<code>comes &lt;div *ngFor="let talk o</code>f talks"&gt;</p>
<p>Original answer:</p>
<p>I missed <code>#</code> in front of <code>talk</code>:</p>
<pre><code class="lang-ts">&lt;div *ngFor=<span class="hljs-string">"#talk of talks"</span>&gt;
</code></pre>
<p>It is so easy to forget that <code>#</code>. I wish the Angular exception error message would instead say:<br><code>you forgot that # again</code>.</p>
<p><a target="_blank" href="https://stackoverflow.com/questions/34012291"><strong>Source</strong></a><br><strong><a class="post-section-overview" href="#599b">Top</a></strong></p>
<h3 id="heading-how-to-add-font-awesome-to-angular-2-cli-project">How to add font-awesome to Angular 2 + CLI project</h3>
<blockquote>
<p>132+ points _? 7<em>1,934+ viewed   
</em><a target="_blank" href="https://stackoverflow.com/users/1394625/nik"><strong>Nik</strong></a> <strong>asked,</strong>_</p>
</blockquote>
<p>I’m using Angular 2+ and Angular CLI.</p>
<p>How do I add font-awesome to my project?</p>
<blockquote>
<p><a target="_blank" href="https://stackoverflow.com/users/5904566"><strong><em>AIon</em></strong></a> <strong><em>answered, (285+ points)</em></strong></p>
</blockquote>
<p>After Angular 2.0 final release, <strong>the structure of the Angular2 CLI project has been changed</strong> — you don’t need any vendor files, no system.js — only webpack. So you do:</p>
<ol>
<li><code>npm install font-awesome --save</code></li>
<li>In the angular-cli.json file locate the <code>styles[]</code> array and add font-awesome references directory here, like below:<br><code>“apps”: [ { “root”: “src”, “outDir”: “dist”, …. “styles”: [ “styles.css”, “../node_modules/bootstrap/dist/css/bootstrap.css”, “../node_modules/font-awesome/css/font-awesome.css” // -here webpack will automatically build a link css element out of this!? ], … } ] ]</code></li>
<li>Place some font-awesome icons in any html file you want:<br><code>&lt;i class=”fa fa-american-sign-language-interpreting fa-5x” aria-hidden=”true”&gt; &lt;/i&gt;</code></li>
<li>Run <code>ng build</code> and <code>ng serve</code> again - because the watchers are only for the src folder and angular-cli.json is not observed for changes.</li>
<li>Enjoy your awesome icons!</li>
</ol>
<p><a target="_blank" href="https://stackoverflow.com/questions/38796541"><strong>Source</strong></a><br><strong><a class="post-section-overview" href="#599b">Top</a></strong></p>
<h3 id="heading-difference-between-http-and-httpclient-in-angular-4">Difference between HTTP and HTTPClient in angular 4?</h3>
<blockquote>
<p>130+ points _? 4<em>7,082+ viewed   
</em><a target="_blank" href="https://stackoverflow.com/users/3551590/aiyoub-amini"><strong>Aioub Amini</strong></a> <strong>asked,</strong>_</p>
</blockquote>
<p>I want to know which one to use to build a mock web service to test the Angular program?</p>
<blockquote>
<p><a target="_blank" href="https://stackoverflow.com/users/2545680"><strong><em>AngularInDepth.com</em></strong></a> <strong><em>answered, (208+ points)</em></strong></p>
</blockquote>
<p>Use the <code>HttpClient</code> class from <code>HttpClientModule</code> if you're using Angular 4.3.x and above:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> { HttpClientModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/common/http'</span>;

<span class="hljs-meta">@NgModule</span>({
 imports: [
   BrowserModule,
   HttpClientModule
 ],
 ...

 <span class="hljs-keyword">class</span> MyService() {
    <span class="hljs-keyword">constructor</span>(<span class="hljs-params">http: HttpClient</span>) {...}
</code></pre>
<p>It’s an upgraded version of <code>http</code> from <code>@angular/http</code> module with the following improvements:</p>
<ul>
<li>Interceptors allow middleware logic to be inserted into the pipeline</li>
<li>Immutable request/response objects</li>
<li>Progress events for both request upload and response download</li>
</ul>
<p>You can read about how it works in <a target="_blank" href="https://blog.angularindepth.com/insiders-guide-into-interceptors-and-httpclient-mechanics-in-angular-103fbdb397bf">Insider’s guide into interceptors and HttpClient mechanics in Angular</a>.</p>
<ul>
<li>Typed, synchronous response body access, including support for JSON body types</li>
<li>JSON is an assumed default and no longer needs to be explicitly parsed</li>
<li>Post-request verification &amp; flush based testing framework</li>
</ul>
<p>Going forward the old http client will be deprecated. Here are the links to the <a target="_blank" href="https://github.com/angular/angular/commit/37797e2">commit message</a> and <a target="_blank" href="https://angular.io/guide/http">the official docs</a>.</p>
<p>Also pay attention that old http was injected using <code>Http</code> class token instead of the new <code>HttpClient</code>:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">import</span> { HttpModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'@angular/http'</span>;

<span class="hljs-meta">@NgModule</span>({
 imports: [
   BrowserModule,
   HttpModule
 ],
 ...

 <span class="hljs-keyword">class</span> MyService() {
    <span class="hljs-keyword">constructor</span>(<span class="hljs-params">http: Http</span>) {...}
</code></pre>
<p>Also, new <code>HttpClient</code> seem to require <code>tslib</code> in runtime, so you have to install it <code>npm i tslib</code> and update <code>system.config.js</code> if you're using <code>SystemJS</code>:</p>
<pre><code class="lang-ts">map: {
     ...
    <span class="hljs-string">'tslib'</span>: <span class="hljs-string">'npm:tslib/tslib.js'</span>,
</code></pre>
<p>And you need to add another mapping if you use SystemJS:</p>
<pre><code><span class="hljs-string">'@angular/common/http'</span>: <span class="hljs-string">'npm:@angular/common/bundles/common-http.umd.js'</span>,
</code></pre><p><a target="_blank" href="https://stackoverflow.com/questions/45129790"><strong>Source</strong></a><br><strong><a class="post-section-overview" href="#599b">Top</a></strong></p>
<p><strong>That’s all for today. if you found this article helpful please help me to share it.</strong> ? ? ?</p>
<p><strong>Follow me on <a target="_blank" href="http://medium.com/wizardnet972">Medium</a> or <a target="_blank" href="https://twitter.com/wizardnet972">Twitter</a> to read more about angular, webpack, typescript, nodejs and javascript! ? ? ?</strong></p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
