Denis Stephanov
Denis Stephanov

Reputation: 5231

Angular 4 condition nested in loop

can you help me fix my code of ng4? I have array of user models, which every have property firstName, lastName, and age like that:

export class User {
    public firstName: string;
    public lastName: string;
    public age: number;

    constructor(fName: string, lName: string, age: number) {
        this.firstName = fName;
        this.lastName = lName;
        this.age = age;
    }
}

Here is my component.ts code:

export class UserItemComponent implements OnInit {
  users: User[];

  constructor() { 
    this.users = [
      new User("John", "", 16),
      new User("Jose", "", 45),
      new User("Xavier", "", 22)
    ]
  }

  ngOnInit() {
  }
}

When I tried it without condition in template, it was working. After I've added condition, I have this issues:

Unexpected closing tag "p". It may happen when the tag has already been closed by another tag.

Do you have idea what I did wrong? Here is code of html template:

<p *ngFor="let user of users">
  <div *ngIf="user.age > 20; then old else young"></div>
  <ng-template #old>Hello, my name is {{user.firstName}} and I'm too old - {{user.age}}.</ng-template>
  <ng-template #young>Hello, my name is {{user.firstName}} and I'm too years young - {{user.age}}.</ng-template>
</p>

Upvotes: 1

Views: 7695

Answers (3)

Kleber
Kleber

Reputation: 1065

Change <div> to <ng-template>:

<p *ngFor="let user of users">
    <ng-template *ngIf="user.age > 20; then old else young"></ng-template>
    <ng-template #young>Hello, my name is {{user.firstName}} and I'm too years young - {{user.age}}.</ng-template>
    <ng-template #old>Hello, my name is {{user.firstName}} and I'm too old - {{user.age}}.</ng-template>
</p>

The reason is that it's not recommended you put a <div> inside a <p>, so Angular throws an error. You can test it doing something like this:

<p><div>This will throw the same error in Angular</div></p>

Upvotes: 1

taras-d
taras-d

Reputation: 1827

p tag can contain only inline elements

Change div to span(inline element)

Why p tag can't contain div tag inside it?

Demo Plunker

Upvotes: 2

Sajeetharan
Sajeetharan

Reputation: 222522

Use div instead of p

<div *ngFor="let user of users">
  <div *ngIf="user.age > 20; then old else young"></div>
  <ng-template #old>Hello, my name is {{user.firstName}} and I'm too old - {{user.age}}.</ng-template>
  <ng-template #young>Hello, my name is {{user.firstName}} and I'm too years young - {{user.age}}.</ng-template>
</div >

Upvotes: 1

Related Questions