如何使用angular2调用单个组件中的多个模板
问题描述:
我是angularJs2的新手。我的要求是我想在单个组件中使用多个模板。就像我有ForgetPasswordComponent
,有两条路线名称为forgot-password
和password/reset
。所以我想在diff路线上调用diff-diff模板。目前forgot-password.component.html
正在呼叫forgot-password
路线,现在我想调用差异。模板password/reset
路线。 这是我的代码。如何使用angular2调用单个组件中的多个模板
APP-routing.module.ts
{ path: 'forgot-password', component: ForgetPasswordComponent },
{ path: 'password/reset', component: ForgetPasswordComponent },
勿忘password.component.ts
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AlertService, AuthenticationService, ForgotpasswordService } from '../_services/index';
//import { AppSettings,IEnvVars } from '../_configs/app.settings';
@Component({
moduleId: module.id,
templateUrl: '../templates/forgot-password.component.html',
providers:[AlertService, AuthenticationService, ForgotpasswordService]
})
export class ForgetPasswordComponent implements OnInit {
model: any = {};
loading = false;
constructor(
private router: Router,
private authenticationService: AuthenticationService,
private forgotpasswordService: ForgotpasswordService,
private alertService: AlertService) { }
ngOnInit() {
// reset login status
this.authenticationService.logout();
}
forgotPassword() {
this.loading = true;
this.forgotpasswordService.forgotPassword(this.model.email)
.subscribe(
data => console.log("yesss"),
error => {
console.log("yesss");
}
);
}
}
答
不知道NG2有内置的方式来支持这一点。我的解决方案是继承。我只是使用一个基本组件类来包含全部或大部分的逻辑和数据,没有html模板。然后在派生组件类中,只需声明构造函数调用super(...),并定义相应的html模板。
如果你的应用程序很复杂,可能你会用模块来实例化类,然后确保你在Component属性中声明了moduleId:module.id,否则NG2运行时可能会抱怨html模板无法加载。