Type casting within a template in Angular 2

后端 未结 3 1742
春和景丽
春和景丽 2020-12-15 16:43

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

相关标签:
3条回答
  • 2020-12-15 16:54

    If you don't care about type control.

    In Angular 8 and higher versions

    [(ngModel)]="$any(event).acknowledged"
    

    https://angular.io/guide/template-typecheck#disabling-type-checking-using-any

    0 讨论(0)
  • 2020-12-15 17:12

    That's not possible because Event can't be referenced from within the template.

    (as is also not supported in template binding expressions) You need to make it available first:

    class MyComponent {
      EventType = Event;
    

    then this should work

    [(ngModel)]="(event as EventType).acknowledged"
    

    update

    class MyComponent {
      asEvent(val) : Event { return val; }
    

    then use it as

    [(ngModel)]="asEvent(event).acknowledged"
    
    0 讨论(0)
  • 2020-12-15 17:19

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

    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;
      }
    }
    

    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).

    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.

    0 讨论(0)
提交回复
热议问题