在Angular 2的模板中进行类型转换 [英] Type casting within a template in Angular 2

查看:224
本文介绍了在Angular 2的模板中进行类型转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个Angular项目(Angular 4.0.0),但在将抽象类的属性绑定到ngModel时遇到了麻烦,因为我首先需要将其转换为实际的具体类才能访问财产.

I'm working on an Angular project (Angular 4.0.0) and I'm having trouble binding a property of an abstract class to ngModel because I first need to cast it as the concrete class it actually is in order to access the property.

即我有一个AbstractEvent类,它有一个具体的实现事件,该事件具有一个布尔属性确认",我需要通过ngModel进行双向绑定以设置一个复选框.

i.e. I have an AbstractEvent class this has a a concrete implementation Event which has a boolean property 'acknowledged' which I need a two way binding via ngModel to set with a checkbox.

我目前在DOM中具有此元素:

I currently have this element in my DOM:

<input type="checkbox" *ngIf="event.end" [(ngModel)]="(event as Event).acknowledged" 
                                          [disabled]="(event as Event).acknowledged">

不幸的是,这引发了以下错误:

Unfortunately this is throwing the following error:

未捕获的错误:模板解析错误: 解析器错误:[(作为事件的事件).已确认]

Uncaught Error: Template parse errors: Parser Error: Missing expected ) at column 8 in [(event as Event).acknowledged]

谷歌搜索似乎暗示这可能是因为在模板中使用'as'不被支持吗?尽管我对此不确定.

Googling around seemed to suggest this might be because using 'as' is not supported when using it inside a template? Although I'm not certain about this.

我也不知道如何在驱动模板的打字稿文件中为其编写函数,因为这会破坏我所需的ngModel的双向绑定.

I also can't work out how to just write a function for it in my typescript file driving the template because this would break the two way binding on ngModel that I require.

如果有人能解决这个问题或正确地在角度模板中执行类型转换,我将不胜感激!

If anyone has any way to get around this or perform type casting in angular templates correctly I would be very appreciative!

推荐答案

如上所述,使用准系统方法调用将对性能产生影响.

As mentioned, using a barebone method call will have performance impact.

更好的方法是使用管道,并且您可以两全其美.只需定义一个Cast管道即可:

A better approach is to use a pipe, and you have best of both worlds. Just define a Cast pipe:

@Pipe({
  name: 'cast',
  pure: true
})
export class CastPipe implements PipeTransform {

  constructor() {
  }

  transform(value: any, args?: any): Event {
    return value;
  }
}

,然后在您的模板中,在需要强制转换时使用event | cast.

and then in your template, use event | cast when you need the cast.

这样,更改检测将保持高效,并且键入是安全的(当然,所请求的类型更改是合理的).

That way, change detection stays efficient, and typing is safe (given the requested type change is sound of course).

不幸的是,由于name属性,我看不到拥有此泛型的方法,因此您必须为每种类型定义一个新管道.

Unfortunately, I don't see a way to have this generic because of the name attribute, so you'd have to define a new pipe for each type.

这篇关于在Angular 2的模板中进行类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆