1

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>
Denis Stephanov
  • 4,563
  • 24
  • 78
  • 174

3 Answers3

2

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

Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
taras-d
  • 1,789
  • 1
  • 12
  • 29
1

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 >
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
1

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>
Kleber
  • 942
  • 1
  • 15
  • 25