2016-05-13 42 views
6

我有一個組件與一個html和.ts文件。出於某些原因,我必須創建多個頁面(HTML)頁面。
是否有可能爲單個類(組件)創建多個(html)頁面?
或者是否可以向組件提供動態TemplateUrl?我可以在angular2中爲一個組件添加兩個模板嗎?

我的主要動機是提供不同的URL和使用不同的視圖(HTML頁面),但使用單個類(.ts類即組件)?
我見過很多問題,下面提及的相關於,但無法找到確切的解決方案爲

我想是這樣的

{ path: '/Login', component: LogIn, name: "Login"}, 
{ path: '/Login2', component: LogIn, name: "Login" }, 
{ path: '/Login3', component: LogIn, name: "Login" } 

我想加載具有不同網址和視圖的相同組件。

+1

那麼什麼是與鏈接的SO問題提供的解決方案的問題? –

+0

他們都沒有爲我工作。 –

+0

他們怎麼不適合你? –

回答

1

角度最佳實踐是一個組件包含一個模板。 如果要將相同的邏輯應用於兩個視圖,則應該在服務中創建該邏輯,併爲兩個不同的組件視圖集使用一個服務。 URL是由路由器處理的不同問題。您應該將組件A分配給URL A,將組件B分配給URL B.

+0

沒有得到你的觀點,請用例子來解釋。 –

+2

他要求在單個服務類中創建具有邏輯的兩個空白組件。你需要兩個不同的網址。 @PardeepJain –

4

這可以通過繼承來實現。不同的視圖和樣式模板,但(基本上)相同的底層組件代碼。你仍然必須聲明@Component元數據,所以如果你使用值訪問器等,你將需要重新定義這些元數據。

第一部分:

import { Component, Input, OnInit } from '@angular/core'; 

import { KeyValuePairBase } from '../../model/key-value-pair-base' 

@Component({ 
    moduleId: module.id, 
    selector: 'select-list', 
    templateUrl: './select-list.component.html', 
    styleUrls: ['./select-list.component.scss'] 
}) 
export class SelectListComponent implements OnInit { 
    @Input() private data: KeyValuePairBase[]; 

    constructor() { 
    super(); 
    } 

    ngOnInit() { 
    if (!this.name) throw new Error("'name' property is required by 'select-list' component"); 
    if (!this.friendlyName) throw new Error(`'friendlyName' property is required by 'select-list' component '${this.name}'`); 
    } 
} 

第二部分:

import { Component } from '@angular/core'; 

import { SelectListComponent } from '../select-list/select-list.component' 

@Component({ 
    moduleId: module.id, 
    selector: 'radio-list', 
    templateUrl: './radio-list.component.html', 
    styleUrls: ['./radio-list.component.scss'] 
}) 
export class RadioListComponent extends SelectListComponent { 
} 
相關問題