Naming conflict in angular template - how to resolve?

38 views Asked by At

I have these two components:

  • JokesList
  • Joke

JokesListComponent:

template:

<app-joke *ngFor="let joke of jokes" [joke]="joke"></app-joke>


@Component({
  selector: 'app-jokes-list',
  templateUrl: './jokes-list.component.html',
  styleUrls: ['./jokes-list.component.css'],
})
export class JokesListComponent {
  public jokes: Array<Joke>;

  constructor() {
    this.jokes = [
      {
        setup: 'What did the cheese say when it looked in the mirror?',
        punchline: 'Hello-Me (Halloumi)',
        hide: true,
      },
      {
        setup: 'What kind of cheese do you use to disguise a small horse?',
        punchline: 'Mask-a-pony (Mascarpone)',
        hide: true,
      },
      {
        setup: 'A kid threw a lump of cheddar at me',
        punchline: 'I thought ‘That’s not very mature’',
        hide: true,
      },
    ];
  }
}

JokeComponent

template

<div class="card card-block">
  <h4 class="card-title">{{ joke.setup }}</h4>
  <p class="card-text" [hidden]="joke.hide">{{ joke.punchline }}</p>
  <a (click)="togglePunchline(joke)" class="btn btn-warnin">Tell Me!</a>
</div>

@Component({
  selector: 'app-joke',
  templateUrl: './joke.component.html',
  styleUrls: ['./joke.component.css'],
})
export class JokeComponent {
  @Input('joke')
  joke!: Joke;

  togglePunchline(joke: Joke) {
    joke.hide = !joke.hide;
  }
}

While running the application, I get an error:

TypeError: Cannot read properties of undefined

This error was reported on the JokesList component's template.

However, when I made this change in the JokesList component's template, it works fine.

<app-joke *ngFor="let j of jokes" [joke]="j"></app-joke>

Just wondering what is causing the problem in the first place and how changing the template variable name solved the issue.

TIA

1

There are 1 answers

0
KodeMagician On

The variable 'joke' is conflicting with the template input property '[joke]'