21

I have Angular 4.3.6 project where a template snippet produces this error.

Template block:

<a [routerLink]="['/article',article?.id]">{{article?.title}}</a>

Error stack trace:

ArticleSpComponent.html:26 ERROR TypeError: Cannot read property 'outlets' of null
    at createNewSegmentGroup (router.es5.js:2967)
    at updateSegmentGroup (router.es5.js:2896)
    at router.es5.js:2914
    at forEach (router.es5.js:593)
    at updateSegmentGroupChildren (

The error cause seems to be obvious. article variable is fetched async from Http and initialized after page is rendered so firstly it's null. However I thought that putting ? after this variable allows to avoid this issue.

Can you please advise?

Sergiy
  • 1,854
  • 4
  • 22
  • 34

2 Answers2

48

? in article?.id is working fine, but the RouterLink directive doesn't like getting a null passed.

You could work around using something like:

<a *ngIf="article" [routerLink]="['/article',article?.id]">{{article?.title}}</a>
<a *ngIf="!article">{{article?.title}}</a>
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 1
    Thank you, Gunter. I thought about such solution. However I suspected there might be a bug in Angular. – Sergiy Aug 31 '17 at 07:56
  • 1
    You could see it as a bug, but it's not clear what `routerLink` should do when it gets `null` as part of the route. I don't see any reasonable behavior. A better error message might be helpful though. Please consider reporting a bug (if there isn't one already) – Günter Zöchbauer Aug 31 '17 at 08:02
  • 8
    I ended up using a similar solution, passing in a default route: `[routerLink]="[ '/article', article?.id || 'all' ]"` – DoubleA Nov 29 '17 at 18:40
  • The double pipe operator alternative worked for me. But I'm still seaking for a not-workaround solution :) Thank you. – romerompb Jul 05 '18 at 20:37
  • I don't think there is one. – Günter Zöchbauer Jul 06 '18 at 03:20
  • DoubleA's answer is the best solution, since it clears all the console errors! – skiabox Mar 18 '19 at 22:30
  • Or you can wrap the same routerLink inside ng-container with ngIf clause for `article`. – Safal Pillai Aug 08 '19 at 13:31
0
 <a  [routerLink]="['/language',language.iso639_1 || 'all']" >{{language.name}}</a>

I was also facing the same issue (Cannot read property 'outlets' of null ) but the above code that I have written, worked for me.

Arghya Sadhu
  • 41,002
  • 9
  • 78
  • 107