One place for hosting & domains

      JavaScript Replace All Instances of a String

      Introduction

      I’ve started building out our JavaScript Glossary and when I got to the replace() method, I had to build out a snippet to handle replacing all occurrences of a string in a string.

      myMessage.replace('sentence', 'message');
      

      https://gist.github.com/chris-sev/7be587f89ba2ee18f105a57a791a2c18

      Normally String replace() only replaces the first instance it finds. If we want JavaScript to replace all, we’ll have to use a regular expression using /g.

      myMessage.replace(/sentence/g, 'message');
      

      https://gist.github.com/chris-sev/452b0b9c2ff1d4ddf1ae3449f90ef595

      In addition to using the inline /g, we can use the constructor function of the RegExp object.

      myMessage.replace(new RegExp('sentence', 'g'), 'message');
      

      https://gist.github.com/chris-sev/fcd4396ee879d3ccc306512a59e2608a

      To replace special characters like -/\^$*+?.()|[]{}) we’ll need to use a \ backslash to escape them.

      Here we’ll replace all the - in this string with just -. I ran into this when building out the Scotch dashboard with markdown trying to escape all my symbols.

      // replace - with -
      myUrl.replace(/-/g, '-');
      
      // or with RegExp
      myUrl.replace(new RegExp('-', 'g'), '-');
      

      https://gist.github.com/chris-sev/d1d233fb4ff5264cd50b8208a03dcf84

      How To Use NgShow and NgHide

      Introduction

      Today we’ll be looking at how we can use Angular’s ngShow and ngHide directives to do exactly what the directives sound like they do, show and hide!

      ngShow and ngHide allow us to display or hide different elements. This helps when creating Angular apps since our single-page applications will most likely have many moving parts that come and go as the state of our application changes.

      The great part about these directives is that we don’t have to do any of the showing or hiding ourselves with CSS or JavaScript. It is all handled by good old Angular.

      To use either ngShow or ngHide, just add the directive to the element you’d like to show or hide.

          
          
          <div ng-show="hello">this is a welcome message</div>
      
           
          <div ng-show="!hello">this is a goodbye message</div>
      
          
          
          <div ng-show="appState == 'goodbye'">this is a goodbye message</div>
      
          
          
          <div ng-hide="checkSomething()"></div>
      

      Once we have that set in our markup, we can set the hello or goodbye variables in a number of different ways. You could set it in your Angular controller and have the div show or hide when your app loads up.

      All of the above can be used for ng-show or ng-hide. This will just hide something if the value, expression, or function returns true.

      See the Pen How To Use ngShow and ngHide by Chris Sevilleja (@sevilayha) on CodePen.

      We will create our link that uses ng-click and will toggle the goCats variable to true or false.

          <a href ng-click="goCats = !goCats">Toggle Cats</a>
      

      Then we can show or hide the cats image using ng-show.

          <img ng-src="http://i.imgur.com/vkW3Lhe.jpg" ng-show="goCats">
      

      ng-src: We use ng-src for the images so that Angular will instantiate and check to see if the image should be hidden. If we didn’t have this, the image would pop up on site load and then disappear once Angular realized it was supposed to be hidden.

      See the Pen How To Use ngShow and ngHide by Chris Sevilleja (@sevilayha) on CodePen.

      Here we evaluate a string coming from our input box. We bind that input box using ng-model to our variable: animal. Depending on what that string is, a different image will show.

      We will bind our input box to a variable called animal.

          <input type="text" ng-model="animal">
      

      Then we will use ng-show to evaluate the string.

          <img ng-src="http://i.imgur.com/vkW3Lhe.jpg" ng-show="animal == 'cat'">
      

      See the Pen How To Use ngShow and ngHide by Chris Sevilleja (@sevilayha) on CodePen.

      Here we will do a simple check to see if the number entered is even or odd. We will create the function in our AngularJS file:

          
          $scope.myNumber = 0;
      
          
          $scope.isEven = function(value) {
      
          if (value % 2 == 0)
            return true;
          else
            return false;
          };
      

      Once we have our function, all we have to do is call it using ng-show or ng-hide and pass in our number. By passing in our number through the function, it keeps our Angular controller clean and testable.

          
          <div ng-show="isEven(myNumber)">
              <h2>The number is even.</h2>
          </div>
      
          
          <div ng-show="!isEven(myNumber)">
              <h2>The number is odd.</h2>
          </div>
      

      With these two great directives, we can do great things with our applications. These are simple examples for showing and hiding elements based on booleans, expressions, and functions, but these three can be used to do many different things for your application.

      Hopefully, this helps when building great AngularJS based applications. In the future, we’ll be talking about animating ngShow and ngHide to create some great moving applications.

      All the Ways to Add CSS to Angular 2 Components

      Introduction

      Writing styles for large applications can be a really challenging task as styles get easily mixed up and confusing. The major issue is usually encountered when trying to structure your styles and give proper naming of individual styles.

      With time, patterns were introduced to enhance style organization and most of these patterns are implemented when we make use of pre-processors like Sass and Less. The significant thing about these patterns is that they suggest organizing our styles and templates in the form of COMPONENTS.

      Angular 2 is component-based which means that every UI functionality is built as a component. Therefore, as component-based styling is a recommended pattern, Angular 2 is just about to make writing styles a rather enjoyable experience. We will discuss different styling techniques and how to use them, but before that, we need to understand the concept of Shadow DOM and View Encapsulation.

      Shadow DOM is included in the Web Components standard by W3C. Shadow DOM basically allows a group of DOM implementations to be hidden inside a single element (which is the basic idea of components) and encapsulate styles to the element. This means that encapsulated styles will only be available for that group of DOM elements and nothing more.

      Abstraction with Shadow DOM

      Remember that the idea of web components and shadow DOM is relatively new and not all browsers can handle the concept. This is where one of the major advantages of Angular 2 comes in as it allows us to choose whether to implement Shadow DOM, just emulate it (default), or not use it at all. This technique of handling Shadow DOM in Angular 2 is known as View Encapsulation.

      The 3 states of view encapsulation are:

      • None: All elements are spit out – no Shadow DOM at all.
      • Emulated: This actually tries to emulate Shadow DOM to give us the feeling that we are scoping our styles. This is not a real Shadow DOM but a strategy to make all browsers smile at our code.
      • Native: This is the real deal as shadow DOM is completely enabled.

      Setting encapsulation is quite simple and is done right inside the @component decorator:

      @Component({
        templateUrl: 'card.html',
        styles: [`
          .card {
            height: 70px;
            width: 100px;
          }
        `],
        encapsulation: ViewEncapsulation.Native
        
        
      })
      

      Now that we have taken some time to put Shadow DOM and View Encapsulation straight, we can go ahead to understand the different techniques of styling an Angular component. Cards are common components that we are familiar with, so permit me to use them for the illustrations.

      Component Inline Styles

      This technique is the most obvious styling technique in Angular 2. This is because it is recommended, makes sense with the concept of components in mind and found everywhere in the Angular 2 documentation. It is implemented in the @Component decorator of our component class like so:

      @Component({
        templateUrl: 'card.html',
        styles: [`
          .card {
            height: 70px;
            width: 100px;
          }
        `],
      })
      

      The expected behavior in various view encapsulation techniques are:

      • None: The style is wrapped in a style tag and pushed to the head.
      • Emulated: The style is wrapped in a style tag, pushed to head, and uniquely identified so it can be matched with its component’s template. With that, the styles will be used for only the template in the same component.
      • Native: Behaves as expected of web components.

      External Stylesheets

      Just like our everyday method of including styles from external styles which have an extension of .css, we could also import external styles in an Angular 2 component. It is as simple as importing templates with the templateUrl property in @Component decorator.

      @Component({
        styleUrls: ['css/style.css'],
        templateUrl: 'card.html',
      })
      

      The expected behavior in various view encapsulation techniques are:

      • None: The style is wrapped in a style tag and pushed to the head. It is appended right after the component inline style.
      • Emulated: The style is wrapped in style tag, pushed to head, and uniquely identified so it can be matched with its component’s template just like the component inline style. As you can see, you must have guessed wrong if you expected the style to be imported with link
      • Native: Behaves as expected of web components.

      Template Inline Style

      This is achievable with two methods:

      1. The styles can be wrapped in a style tag and placed before the templates:
      @Component({
        template: `
          <style>
          h1 {
            color: purple;
          }
          </style>
          <h1>Styling Angular Components</h1>
          `
      })
      
      1. The style can be written as normal inline styles in the template tags:
      @Component({
        template: '<h1 style="color:pink">Styling Angular Components</h1>'
      })
      

      The expected behavior in various view encapsulation techniques are:

      • None: For method 1, the style is wrapped in a style tag and pushed to the head. It is appended right after the component inline and external styles. For method 2, the style just remains in the tag.
      • Emulated: For method 1, the style is wrapped in style tag, pushed to head, and uniquely identified so it can be matched with its component’s template just like the component inline style. For method 2, the style still remains in the tag.
      • Native: Behaves as expected of web components.

      This is the point where we need to pay attention as it can be quite tricky. If you have been following the article carefully, you will realize that component styles, if any, are always appended to the head first.

      Where it then becomes confusing is that in the first method of template inline styles are appended before the external styles. This makes external styles take precedence because in CSS the last is the greatest.

      Playing With the Demo

      To better understand priorities, I have created a Plunk with all the styling techniques we discussed. What I suggest is that you switch these styles, mess around with them and see the results. The comment section of this article is a great place to discuss your findings.

      Whatever method you choose is accepted and that is the good thing about components and Angular 2. You don’t have to listen to the preaching of not using internal styles or inline styles as they are within components and will be scoped. On the other hand, we are now able to organize our code better in a modular pattern.

      Angular 2 is awesome, right?