In AngularDart, how should I reference my templates in templateUrl so they work for both Dartium and dart2js?

Issue

I currently have this directory layout:

project
    web
        app.html
        main.dart
        templates
            app.html
            alerts.html
            menu.html
        components
            AppComponent.dart
            AlertsComponent.dart
            MenuComponent.dart
        resources
            css
                bootstrap.css

My components look like:

@Component(
    selector: 'app',
    templateUrl: 'templates/app.html'
)
class AppComponent { ... }

My application’s index.html (in another project) is served from /client, and project/web is served from /project. The above works in Dartium, but I get errors from pub build:

[Warning from _Serial on project|web/main.dart with input project|web/components/AppComponent.dart]:
line 3, column 1 of web/components/AppComponent.dart: Unable to find templates/app.html at project|templates/app.html
@Component(
^^^^^^^^^^^

and

[Warning from _Serial]:
Unable to find webatara|web/main.dart from html_files in pubspec.yaml.

and

[Warning from TemplateCacheGenerator]:
Can't find asset web/web/templates/app.html.

depending on what combination of paths I use in templateUrl and html_files (for Angular’s transformer).

What, exactly, should go where and how should it be referenced in templateUrl and pubspec.yaml?

Update: I can get rid of my build errors by moving my templates to the lib directory and using templateUrl: 'packages/project/templates/app.html', but then Dartium tries to load that as /packages/project/templates/app.html, and not /project/packages/project/templates/app.html, which would be correct. I don’t see any way to tell it what the base URL is.

Solution

but then Dartium tries to load that as
/packages/project/templates/app.html, and not
/project/packages/project/templates/app.html, which would be correct.
I don’t see any way to tell it what the base URL is.

I believe you are using angulardart 1.1.1 or 1.1.2? We had the same issue in our project after switching from 1.1.0 to 1.1.2. This is weird behaviour that was added since version 1.1.1.

For some reason default package root in AngularDart now is ‘/packages/’. This causes generation of root-relative URLs. In your case it generates

/packages/project/templates/app.html

instead of

packages/project/templates/app.html

It’s OK while you app is in the root of your domain. But in your case what you need to do is to add following to your initialization method in main.dart:

bind(ResourceResolverConfig, toValue: new ResourceResolverConfig
         .resolveRelativeUrls(true, packageRoot: 'packages/'));

This will override angular’s default packages root and will make it generate correct relative URLs.

Hope it helps.

Answered By – Lev Sivashov

Answer Checked By – Cary Denson (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *