1 year ago

#280306

test-img

kcinkcinkcinnick

Angular enable/disable form inputs based on async pipe object variable in template

How can I hide/show input fields based on variables of an async-piped object?

What I currently have:

A video-detail form with an async pipe to retrieve the video.
<ng-container *ngIf="video$ | async as video"></ng-container>

This video is of type VideoDto containing a bunch of variables.
A video can be either a movie or a serie based on what variables are undefined.
For example if video.duration has a value, then it's a movie.
If video.seasons & video.avg_duration has a value, then it's a serie.
Since I don't want to make 2 seperate components (form for MovieDetails, form for serieDetails), I would like to hide the input fields.

If video.duration has a value when video is retrieved, then the input-field of duration should show and the input-fields of seasons & avg_duration should hide.

Here is a simplified version of what I currently have:

<ng-container *ngIf="video.duration; then movieBlock else serieBlock"></ng-container>

<ng-template #movieBlock>  
         <input type="number" [(ngModel)]="video.duration" name="duration">  
</ng-template>

<ng-template #serieBlock>  
          <input type="number" [(ngModel)]="video.seasons" name="seasons">
          <input type="number" [(ngModel)]="video.avg_duration" name="avg_duration">
</ng-template>

When it's a movie and I clear the duration input field, the *ngIf updates this so the Movieform becomes a Serieform since duration is zero.

Vice versa when I go to the details page of a Serie and clear the seasons & avg_duration input field it turns into a movie form...

Even using combinations like *ngIf="duration && (!seasons || !avg_duration) can make it break.

Is there a way to only check for the duration value once when video is retrieved and then stop listening to any updates?

I tried adding a "type" field to the videoDto class where type get's set in the constructor based on the duration variable, but the async pipe won't use the constructor.

Is there another way of determining the type? First I tried to accept either a Movie or a Serie but after struggling with it for to long I created the VideoDto.

Any help would be much appreciated.

angular

forms

hide

angular-ng-if

0 Answers

Your Answer

Accepted video resources