Angular2如何基于activatedRoute呈现不同的模板';s queryParams
我有一个当前加载特定模板的组件,即加载Angular2如何基于activatedRoute呈现不同的模板';s queryParams,angular,Angular,我有一个当前加载特定模板的组件,即加载/load usersurl时的templateA @Component({ selector: 'app-load-users', templateUrl: './load-users.component.html', }) export class LoadUsersComponent implements OnDestroy, OnInit {...} 如果url稍有不同,我想加载一个非常类似的模板,例如/load users/new=tru
/load users
url时的templateA
@Component({
selector: 'app-load-users',
templateUrl: './load-users.component.html',
})
export class LoadUsersComponent implements OnDestroy, OnInit {...}
如果url稍有不同,我想加载一个非常类似的模板,例如/load users/new=true
。当前的组件代码可以重用,除了一些更改,只是新模板需要看起来有点不同。如何根据查询参数new
的值加载不同的模板
if (new) {
show new template
} else {
show current 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>
您可以尝试使用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>
在我看来,将新模板制作成一个组件将是一个好主意,有助于保持代码的简洁性和组织性