Jon Sud
Jon Sud

Reputation: 11671

should I use one component for edit and view with ngif or divided them to components?

In my angular application I have two urls: localhost:4200/report/11/view and localhost:4200/report/11/edit.

In view page I divide the areas to components like this: --> render h2 with title. -> render ul-li with list of companies belong to this report. -> render p.

In my edit page I make those component editable: --> render input with title. -> render ul-li with list of companies belong to this report, and autocomplete to add to the list. -> render input.

My question is should I use seperate components for view and edit or inside the component I use ngIf to display or not the right part?

Upvotes: 0

Views: 1651

Answers (3)

Prashant Pimpale
Prashant Pimpale

Reputation: 10717

I would use two separate components for both Edit and View the data:

  1. To maintain clean code i.e No need to deal with structural directives like *ngIf etc to render HTML controls.
  2. If you made changes in one feature then you have to test both feature (which is TDS and Error prone)
  3. Better to maintain and easy to understand -- In case if you want to add new text box if a Edit module then no need to add if to render it
  4. Separate of Concern - As both functionality is different so keep it separate

Upvotes: 3

Hope
Hope

Reputation: 495

You can use inline edit or you can use <ng-container> based on *ngIf Like:

In your TS file:

edit: boolean = true
// Other code ...

In your template:

<ng-container *ngIf="edit === false">
   <!-- your snippet when edit mode is off. -->
</ng-container>
<ng-container *ngIf="edit === true">
   <!-- your snippet when edit mode is on. -->
</ng-container>

Upvotes: 2

Ankit Kumar Singh
Ankit Kumar Singh

Reputation: 557

Since there is not predefined pattern it totally depends on how you want it to extend in future to make the code more reusable.

So yes, you can create a single component to handle both edit and view screen by maintaining a flag and rendering the required view.

For a more reusable approach. You can follow the design patterns something like creating an abstract class for the view and extending them to all your common components. In this way your code will be clean in any scenario, and support extensibility in future.

Upvotes: 3

Related Questions