David Barker
David Barker

Reputation: 14620

Reference outer component in ngFor

As an example I have a basic component with two public properties (for brevity I have ommited the outer FormGroup from the example.

public sentiment: FormArray;
public sentimentValues: ['terrible', 'neutral', 'good'];

In the view I am iterating over the controls that are contained in the sentiment array.

<div *ngFor="let option of sentiment.controls; index as i;">
    <label [for]="'sentiment_' + i" class="sentimentLabel">
      <input class="sentiment"
             [id]="'sentiment_' + i"
             type="checkbox"
             name="sentiment"
             [formControl]="option"
             value="option1">
    </label>
</div>

I would like to add a class to the label element that is at the index of i in the sentimentValues array within an ngFor loop.

<label [ngClass]="sentimentValues[i]">...</label>

This yields an error _co.sentimentValues is undefined

How can I access the outer components value within the ngFor loop? (or how can I re-factor this so that maybe the sentimentValues array is just not required?

(Additional but related, the [value] of the input should also be the value of sentimentValues[i])

Upvotes: 0

Views: 52

Answers (1)

Syntactic Fructose
Syntactic Fructose

Reputation: 20084

EDIT:

Your array initialization is incorrect, you need to be using =:

public sentimentValues = ['terrible', 'neutral', 'good'];

Upvotes: 1

Related Questions