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>
答案 0 :(得分:1)
答案 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>