DEV Community

Cover image for Angular: Is View Code Immutable?
John Peters
John Peters

Posted on • Edited on

Angular: Is View Code Immutable?

Scenario: We have a working view, but new specs ask to add another select html element only used on special occasions. We don't want to change the working view due to the Open/Closed principle, instead we want to modify it. Are Views Immutable?

The Mutable Way:
Just add ng-content tag into existing view. This mutates the code and subsequent View when displayed.

<working-component
   [firstOptions]="firstOptions"
>
... has other working stuff above.

<ng-content></ng-content> //Mutation here

... other working stuff below.
</working-component>
Enter fullscreen mode Exit fullscreen mode

How to use:

<working-component
   [firstOptions]="firstOptions"
>
   //Here we add our new content!
   <ourNewComponent
      [options]="things"
   >
   </ourNewComponent>
</working-component>
Enter fullscreen mode Exit fullscreen mode

Adding the ng-content code we are able to inject our new content without impacting the existing code. We are using a view layer compositional technique.

The Immutable Way

<app-working
   [firstOptions]="firstOptions"
>
</app-working>
<ourNewComponent
      [options]="things"
>
</ourNewComponent>
Enter fullscreen mode Exit fullscreen mode

In this method we simply add our new component after the working component and use styling to make them look like the same single component. We are not altering the original view.

The functions to save the changes just require the addressibility to both components using either design. Option 2 follows the Open/Closed Principle. Option 1 follows Compositional Rules. Either way, just make sure the code is atomic for each.

There is a third way which is to crack open the original component and insert a new select element. It will need to be hideable based on the specs. and showable only on special occasion. This is the least favorable option.

Top comments (0)