0

Let's say I have two routes in Angular 14: user and admin. I also have a component called some-content.

user.component.html:

<app-some-content></app-some-content>

admin.component.html (same as user.component.html):

<app-some-content></app-some-content>

some-content.component.ts:

export class SomeContentComponent implements OnInit {
  constructor(private _router: Router) { }
  router: Router = this._router;

some-content.component.html:

<table>
  <thead>
    <th>Last name</th>
    <th>First name</th>
    <th>Some stuff</th>
    <th>Some other stuff</th>
  </thead>
  <tbody>
    <tr *ngFor="let person of persons">
      <td>{{person.lastName}}</td>
      <td>{{person.firstName}}</td>
      <td *ngIf="router.url === '/user'">{{person.someStuff}}</td>
      <td *ngIf="router.url === '/admin'" (click)="callSomeFunction()">{{person.someStuff}}</td>
      <td *ngIf="router.url === '/admin'">
        <!-- html stuff -->
      </td>
    </tr>
  </tbody>
</table>

As you can see, I used the Router service property url with *ngIf to show/hide data based on the actual view. Just a few lines of code needed, but is it the proper way to do things?

Tomo
  • 429
  • 1
  • 10
  • 24
  • You shouldn't link your state directely to your URL. – Matthieu Riegler Oct 03 '22 at 13:44
  • This works. But it’s probably better to handle this in the user component itself and use an input on the some-content component that tells it to render itself or not (or even use an *ngIf directly on the some-component. The idea to keep presentational component as dumb as possible. – MikeOne Oct 03 '22 at 14:27
  • Honestly I tried with `@Input` and calling methods from other controllers, but things went messy and it didn't work at all. – Tomo Oct 03 '22 at 14:55
  • Is it better to have two very similar *component.html* files with some duplicated methods in the two *component.ts* files? – Tomo Oct 04 '22 at 14:27

0 Answers0