Dart - Geek went Freak!

Dart

Angular Dart 2: Conditionally apply CSS classes

Angular 2 provides NgClass directive to conditionally apply CSS classes to elements.

NgClass is available when Angular2 is imported using:

import 'package:angular2/angular2.dart';

First step is to inform Angular that NgClass is being used in the view.

@View(
    ...
    directives: const [NgClass]
    ...
)

Lets declare a variable in our component that is used to conditionally change CSS class.

class CSSSwitcher {
    ...
    bool status = false;
    ...
}

Use NgClass directive in the view

Finally, lets implement the toggleStatus funciton that toggles the status.

class CSSSwitcher {
  ...
  void toggleStatus() {
    status = !status;
  }
  ...
}

Here is the complete code:

NgClass takes a Map of String keys and bool values. The keys whose values evaluated to true are added to the element’s class. To added multiple class one can add multiple items to this map:

Here is the complete code that adds multiple classes conditionally:

NgClass can also take a String and a List of Strings. Here is an example with List of Strings:

Dart: SVG to image in Dart

You can convert SVG to image in Dart using the following code snippet:

In this code, the SVG is constructed using dart:svg library. The svg document is obtained using outerHtml property of SvgSvgElement. The SVG document if converted into data URI. This data URI can be later used as scr of Image or background-image of any element.

Dart: Getting elements to accept drops using HTML5 DnD

Using HTML5 Drag-n-Drop could be little bit tricky, because it doesn’t work out of the box. If you want to listen to on-mouse-down or on-key-down events on an element, you would do it like this:

HtmlElement element = queryselector("#my-element");
element.onMouseDown.listen((MouseEvent e) {
  print("Please don't click me hard next time! Thanks for understanding :)");
});

So, it should be that simple to get on-drop event to work right? No! If you try this code, you will be disappointed to find out that, it doesn’t work at all.

HtmlElement element = queryselector("#my-element");
element.onDrop.listen((MouseEvent e) {
  print("Drop 'em on me!");
});

So why? From the beginning of HTML, when you drop something into a web page, it is thought to be a link and the browser tries to navigate there.

So? So, you have to disable this default behavior. This is how you do it:

HtmlElement element = queryselector("#my-element");
element.onDrop.listen((MouseEvent e) {
  print("Don't drop 'em too fast, you could break them.");
});

element.onDragOver.listen((event) {
  event.preventDefault();
});

Can you notice how we prevent default behavior in onDragOver event by calling preventDefault on the event? That does the trick!

Happy Darting!!!!