Angular 4条件嵌套在循环中

时间:2017-07-29 13:30:35

标签: angular angular-ng-if

你可以帮我修复我的ng4代码吗?我有一系列用户模型,每个模型都具有属性firstName,lastName和age:

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;
    }
}

这是我的component.ts代码:

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

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

  ngOnInit() {
  }
}

当我在模板中无条件地尝试它时,它正在工作。在我添加条件后,我遇到了这个问题:

  

意外的结束标记“p”。标签已经存在时可能会发生   已被另一个标签关闭。

你知道我做错了什么吗?这是html模板的代码:

<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 个答案:

答案 0 :(得分:1)

p 标记只能包含内嵌元素

div更改为span(内联元素)

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

Demo Plunker

答案 1 :(得分:1)

使用 div 代替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 >

答案 2 :(得分:1)

<div>更改为<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>

原因是不建议您在<div>内放置<p>,因此Angular会抛出错误。你可以测试它做这样的事情:

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