Last Updated: February 25, 2016
· iaincampbell

Observing model changes in Polymer Dart

Polymer expressions can be tricky when bound to model properties. The docs on Observables aren't quite there, and there's lots of outdated information flying around the interwebs.

I was looking to alter the text on a button based on whether a model's id field was null or not.

<button on-click="{{save}}" type="button">
<template if="{{exists}}">Edit</template>
<template if="{{!exists}}">Add</template>

I initially had the following:

bool exists => !(id==null);

The thing is, no change events were being fired when the model properties were updated. It turns out that the solution is to bind to a dummy variable and update that by tracking changes to the model properties:

import 'package:polymer/polymer.dart';
import 'dart:mirrors';
import 'mymodel.dart';

class MyModelForm extends PolymerElement {

  @observable MyModel model = new MyModel();
  @observable bool exists = false;  

  MyForm.created() : super.created();

  void attached() {

  _trackChanges(changes) {
    changes.forEach((PropertyChangeRecord record) {
        exists = !(record.newValue==null);        

A PropertyChangeRecord returns a List of Symbols so I needed the Mirror library to extract the actual field name.