1

Been working on figuring out an issue I've run into working on some existing code.

It's a component with a selector in the HTML that looks like this:

<div my-component [option1]='hello' [option2]='world'></div>

and a template with this structure (paraphrased):

<div>
    <span>{{content1}}</span>
    <ng-container *ngFor="...">
        <span>{{content2}}</span>
    </ng-container>
</div>

Variable 1 and 2 are set up as @Inputs

They are optional. So what we're wanting to do is check to see if they've been given a value in the selector. If so, we set a variable in the template to that value. Essentially passing the variable value from the selector into our template to render things out.

So the logic for the first looks like this:

ngAfterContentInit() {
    if (this.variable1) {
        this.content1 = this.variable1;
    }
}

this works just fine. The template renders content1 as the value of variable1 that was passed in via the @input.

However, I can not put the same logic for variable2 in ngAfterContentInit(). Doing so results in this.content2 being null.

I discovered that I can put that same logic to set this.content2 inside of the ngAfterViewChecked() hook and it will work there. However, it only 'takes' the second time ngAfterViewChecked() is called (and every time thereafter).

My only thinking is that the first lifecycle hook isn't waiting for the for-loop to complete. I feel I'm missing an understanding of passing variables into a template when a for-loop exists.

At the moment, my solution is to grab variable2's value in ngAfterContentInit() and pass it to a 3rd variable that I then use to set content2 in ngAfterViewChecked(). I have a counter so I only attempt setting it twice (any further calls to ngAfterViewChecked() will not try and reset content2)

This feels extremely ugly, though!

DA.
  • 39,848
  • 49
  • 150
  • 213
  • Could you maybe try to set up a stackblitz demo ? Also, did you try using `ngOnChanges`? – David Aug 02 '18 at 09:48

0 Answers0