“Angular 2 could not understand the value in View#template” using $event

青春壹個敷衍的年華 提交于 2019-12-14 02:22:42

问题


I can't get $event working. Example:

import 'package:angular2/core.dart';

@Component(
    selector: 'my-app', 
    template: '''
        <h1>{{title}}</h1>
        <button (click)="onTest($event)">testing</button>
    ''')
class AppComponent {
    String title = 'Testing event';

    onTest(event) {
        print(event);
    }
}

When I let pub serve the app, I throws a build error:

Build error:
Transform DirectiveProcessor on file_transfer|lib/app_component.dart threw error: Angular 2 could not understand the value in View#template.
'''
        <h1>{{title}}</h1>
        <button (click)="onTest($event)">testing</button...
package:angular2/src/transform/common/type_metadata_reader.dart 164:5   _expressionToString
package:angular2/src/transform/common/type_metadata_reader.dart 920:17  _CompileTemplateMetadataVisitor._populateTemplate
package:angular2/src/transform/common/type_metadata_reader.dart 901:9   _CompileTemplateMetadataVisitor.visitNamedExpression
package:analyzer/src/dart/ast/ast.dart 7455:15                          NamedExpressionImpl.accept
...

I also tried to change the (click) into ng-click as here $event in AngularDart 1.0 is not available anymore - what is the alternative? but it didn't help.

I'm new to angular, but the code above should work, right? I looked at https://webdev.dartlang.org/angular/guide/template-syntax#!#event-binding and the heroes example where $event is used too. Can't see any difference...

Any help is appreciated.


回答1:


This snippet would work fine if the template was in its own file.

However, since the template is in a .dart file, any $variable in a string will be evaluated to the value of variable in that context.

In this case, either of the following will make this work:

  1. Escape the $ in the template. Replace

<button (click)="onTest($event)">testing</button>

with

<button (click)="onTest(\$event)">testing</button>

  1. Use a raw string as the template:

template: r''' ...template content... ''')



来源:https://stackoverflow.com/questions/41385952/angular-2-could-not-understand-the-value-in-viewtemplate-using-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!