How to build an inplace edit with dart angular

Issue

I’m very impressed by the angularjs example that writes directly to a div (without having to hide/show an )

https://docs.angularjs.org/guide/forms (section Implementing custom form controls (using ngModel))

    angular.module('form-example2', []).directive('contenteditable', function() {
  return {
    require: 'ngModel',
    link: function(scope, elm, attrs, ctrl) {
      ctrl.$render = function() {
      elm.html(ctrl.$viewValue);
    };
}});

I actually don’t understand who intercepts the keyup event to put it into the $viewValue and write it back to the div, so I’m unable to reproduce this feature in dart angular.

Can anybody explain what’s happening behind the scene for that div with the directive? How would AngularDart code for this look like?

Solution

You can write your own directive and tune the interactions and update calls exactly as you like. (Choose how to deal with blur, keyup, keydown event etc.) Here’s how I did it. It’s a basic example how to build custom directive with two-way binding with Angular 2 and Dart (AngularDart).

contenteditable.dart

import 'dart:html';
import 'package:angular2/core.dart';

@Directive(
  selector: '[contentEditable]', //Selector that you'll use in your templates
)
class ContentEditable implements OnChanges {
  Element _el; //holding element's properties and content

  @Input()
  String contentEditableModel;

  @Output()
  EventEmitter contentEditableModelChange = new EventEmitter();

  //Constructor
  ContentEditable(ElementRef ref) {
    _el = ref.nativeElement;
  }

  //This method is called on blur event (can be also 'keyup', 'keydown' etc.)
  @HostListener('blur')
  void onBlur() {
    contentEditableModelChange.emit(_el.text);
  }

  //This implementation updates the editable elements content
  //when model is updated somewhere else
  @override
  ngOnChanges(Map<String, SimpleChange> changes) {
    changes.forEach((String propName, SimpleChange change) {
      _el.innerHtml = change.currentValue;
    });
  }
}

And here’s how to use the directive (that you just created) in your component…

my_component.dart

import 'package:angular2/core.dart';
import 'package:angular2_components/angular2_components.dart';

import 'contenteditable.dart';

@Component(
  selector: 'my-component',
  styleUrls: const ['app_component.css'],
  templateUrl: 'my_component.html',
  directives: const [ContentEditable],
)

class MyComponent {
  String some_var = "Hello editable!";
}

my_component.html

<div contentEditable [(contentEditableModel)]="some_var">Some text that's overridden by some_var</div>
<h1>Here you see the value updating: {{some_var}}</h1>
And from here you can update it too: <input [(ngModel)]="some_var">

Answered By – ainla

Answer Checked By – Senaida (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.