我有一个组件,该组件当前在加载/load-users
URL时加载特定模板templateA。
@Component({
selector: 'app-load-users',
templateUrl: './load-users.component.html',
})
export class LoadUsersComponent implements OnDestroy, OnInit {...}
如果网址略有不同,例如,我想加载一个非常相似的模板。 /load-users/new=true
。当前的组件代码可以重复使用,除了一些更改之外,只是新模板需要看起来有所不同。如何根据查询参数new
的值加载其他模板?
if (new) {
show new template
} else {
show current template
}
我环顾四周,似乎有一个单独的组件是建议,但我会重复很多代码。任何建议都会有所帮助。
仅包含另一个组件的建议很丰富,这是唯一的方法吗?
Is there any way to render two or more templates from one component? Angular2
答案 0 :(得分:0)
每个组件只能有一个模板。
但是您可以使用<ng-template>
来渲染其他内容。
load-user.component.ts
export class LoadUsersComponent implements OnDestroy, OnInit {
new: Boolean
someData: any;
.
.
.
}
load-user.component.html
<div *ngIf="new; else theOtherTemplate">
<child-component-with-the-first-template [data]="someData"></child-component-with-the-first-template>
</div>
<ng-template #theOtherTemplate>
<child-component-with-the-first-template [data]="someData"></child-component-with-the-second-template>
</ng-template>
答案 1 :(得分:0)
您可以尝试将param用作某种类型的布尔指示,以指示模板上显示的内容
@Component({
selector: 'app-load-users',
templateUrl: './load-users.component.html',
})
export class LoadUsersComponent implements OnDestroy, OnInit {
isNew: boolean = false;
constructor(private activatedRoute: ActivatedRoute) {}
ngOnInit() {
this.activatedRoute.queryParams.subscribe(params => {
isNew = params['new'];
}
}
}
比html中的类似:
<div *ngIf="!isNew>
<original-template></original-template>
</div>
<div *ngIf="isNew>
<new-template></new-template>
</div>
在我看来,将新模板制成组件将是一个好主意,并且有助于保持代码的简洁性和组织性