Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type casting within a template in Angular 2

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.

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.

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]

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.

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!

like image 628
Plog Avatar asked Aug 30 '17 15:08

Plog


People also ask

Does Angular have template type checking?

Overview of template type checkinglink. Just as TypeScript catches type errors in your code, Angular checks the expressions and bindings within the templates of your application and can report any type errors it finds.

What is type casting in Angular?

Type castings allow you to convert a variable from one type to another. In TypeScript, you can use the as keyword or <> operator for type castings.

What is the purpose of any type cast function in Angular?

The $any() type cast functionlink Using $any() prevents TypeScript from reporting that bestByDate is not a member of the item object. The $any() cast function also works with this to allow access to undeclared members of the component.


1 Answers

If you don't care about type control.

In Angular 8 and higher versions

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

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

@Component({   selector: 'my-component',   template: '{{$any(person).addresss.street}}' }) class MyComponent {   person?: Person; } 
like image 78
Muhammet Can TONBUL Avatar answered Sep 23 '22 04:09

Muhammet Can TONBUL