1

I have given a name using the #var notation to an angular component (app-backtester-chart) created by me, but I don't understand why I don't seem to be able to reference it outside of the div it is in? I'm clearly missing something here...

  {{chartcmp.width}}
  <div class="row">
    <div class="col" *ngIf="thisStrategy">
      {{chartcmp.width}}
      <app-backtester-chart #chartcmp
                          [inputStrategy]="thisStrategy"
                          [showBenchmark]="showBenchmark">
      </app-backtester-chart>
    </div>
  </div>

The first {{chartcmp.width}} generates an error: Cannot read property 'width' of undefined

So why does the second one inside the div works, and correctly displays the width?

From the Angular documentation (Template reference variables):

You can refer to a template reference variable anywhere in the component's template.

I can't find an explanation anywhere. Any help would be greatly appreciated.

3 Answers 3

2

It's beacause of the *ngIf. You can't access a template reference variable if it's not rendred.

Sign up to request clarification or add additional context in comments.

Comments

1

I think it's because your *ngIf if you're doing an ngIf all div inside are not constructed as well as your variable ^^

2 Comments

Ok, removing the *ngIf it works, so thanks for that, but I still don't get the rationale. If the condition of the *ngIf evaluates to "true" then what's inside it gets constructed, which is exactly what happens in my code. So why would the variable not exist outside of it? Is its scope limited by the existence of the *ngIf, like in C# for example what is inside the curly brackets defines a new scope? I can't find a clear answer anywhere.
0

Try this for first one

{{chartcmp === null? "" : chartcmp.width}}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.