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>

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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 >

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.