Friday, November 24, 2017

The selector "app-root" did not match any elements

Hi Guys,

You might face this error when we try add a newly created component in Angular 2/4/5.

Let's have a look at the complete stack trace:


ERROR Error: The selector "app-root" did not match any elements
    at DefaultDomRenderer2.selectRootElement (platform-browser.js:2791)
    at DebugRenderer2.selectRootElement (core.js:14962)
    at createElement (core.js:10279)
    at createViewNodes (core.js:13409)
    at createRootView (core.js:13338)
    at callWithDebugContext (core.js:14739)
    at Object.debugCreateRootView [as createRootView] (core.js:14040)
    at ComponentFactory_.create (core.js:10959)
    at ComponentFactoryBoundToModule.create (core.js:3919)
    at ApplicationRef.bootstrap (core.js:5730)
This would come if you have placed the newly created component selector in the root component .

Let's look at the working code:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>MyFirstApp</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root></app-root>

</body>
</html>

Remember this code is working fine , now lets see the erroneous code.
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>MyFirstApp</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-mycomponent></app-mycomponent>
</body>
</html>

So the error is due to the app-mycomponent which is not present. So , how to fix this error ? You need to add the new component in the app component , not in the index.html.
<app-mycomponent></app-mycomponent>
<div style="text-align:center">
  <h1>
    Welcome  {{title}}!
  </h1>
  <img width="300" src="xyz">
</div>
Now, we see the output as:
mycomponent works!

Refer to similar answers in Stack Overflow site.

Sunday, November 12, 2017

Lexical scoping in JavaScript

If you are familiar with JavaScript you might be aware that JavaScript uses lexical scoping . Now what really is lexical scoping and how is it different than other languages like java ?
What is actually a scope ? A scope is the visibility and accessibility of the variable . So when a JavaScript function tries to refer to a variable , the scope of the variable comes into play . Now lexical scoping means the variable will be accessible to the function only if it was in scope when it was defined.
The key point is variable does have different scopes while definition and execution.

ec2-user@ec2 Permission denied