Search code examples
angular-dart

Using String extension method defined in library in angular dart template


I created String class extension and trying to use new method in angular dart template. But webapp build fails because of new method wasn't found. How can I use extension methods in template?

Here is String extension string_utils.dart:

extension NullChecking on String? {
  bool isNullOrEmpty() => this?.isEmpty ?? true;
  bool isBlank() => this?.trim().isNullOrEmpty() ?? true;
  bool isNotBlank() => !this.isBlank();
}

extension BlankChecking on String {
  bool isNotBlank() => !this.isBlank();
}

Here is library file facade.dart:

library facade;

export 'src/string_utils.dart';

And here is component with template:

import 'package:facade/facade.dart';
import 'package:ngdart/angular.dart';

@Component(
  selector: 'my-app',
  template: '<h1>Hello {{name}}</h1><div>Name.isBlank(): {{name.isBlank()}}</div>',
)
class AppComponent {
  var name = 'Angular';
}

Here is error in console when I try to build it:

[SEVERE] build_web_compilers:ddc on lib/app_component.template.ddc.module: Error compiling dartdevc module:angular_tour_of_heroes|lib/app_component.template.sound.ddc.js

packages/angular_tour_of_heroes/app_component.template.dart:51:67: Error: The method 'isBlank' isn't defined for the class 'String'.
Try correcting the name to the name of an existing method, or defining a method named 'isBlank'.
    this._textBinding_5.updateText(import9.interpolate0(_ctx.name.isBlank())) /* REF:asset:angular_tour_of_heroes/lib/app_component.dart:172:190 */;

All this code is available in github.


Solution

  • As angular template imports your component class you can use export for your extension.

    import 'package:ngdart/angular.dart';
    
    export 'package:facade/facade.dart';
    
    @Component(
      selector: 'my-app',
      template: '<h1>Hello {{name}}</h1><div>Name.isBlank(): {{name.isBlank()}}</div>',
    )
    class AppComponent {
      var name = 'Angular';
    }