2016-11-12 67 views
0

有人能解釋我在@Component({})中是什麼意思「模板」。例如,我創建我的組件什麼是組件Angular2中的模板

@Component({ 
selector: 'delete' 
template: 'What i must write here?. If i write code here, this code will be at view? or i should write code here and the same in view? 

我讀過的文件,但不能明白這個是什麼零部件

+1

請檢查https://angular.io/docs/ts/latest/guide/應該有足夠的例子在那裏,使它相當清楚'模板'應該包含什麼。你問過之前是否嘗試過搜索? –

回答

3

您通過定義視圖看起來應該像Angular2創建的HTML template。或者,您可以將templateUrl與路徑傳遞給應該用於創建視圖的HTML文件。

+0

如果我爲組件編寫簡單模板,並在視圖中編寫此組件。這個teplate將被初始化並顯示在視圖中? –

+0

是的,這就是主意。 –

+0

但如果我alreay有代碼的HTML視圖,並且當我在控制器上創建新組件(此控制器具有用於查看templeteURL的組件)並在此新組件上編寫模板時,我的html代碼將更改爲模板代碼? –

1

模板是您正在創建的組件的html視圖。所以通常我喜歡做的就是創建兩個文件,

myfile.component.ts myfile.component.html

在TS文件是打字稿/ JavaScript的邏輯視圖,

在html文件是視圖的html,並且是將被查看的頁面。

然後在TS文件模板字段中指定的路徑,HTML文件,

的.ts文件

@Component({ 
    templateUrl: './myfile.component.html', 
}) 
export class MyfileComponent { 

    constructor() { } 

} 

.html文件

<div> 
My html file is being viewed now! 
</div> 

您也可以直接服務.ts文件中的html。要做到這一點,你可以使用模板而不是templateUrl那麼你就不需要html文件。

@Component({ 
     template: ` 
    <h1>My First Angular 2 multiline template</h1> 
    <p>Second line</p> 
    ` 
    }) 
    export class MyfileComponent { 

     constructor() { } 

    } 

通知,其中蜱,它必須被格式化那樣。

因此簡化多個視圖,在我的應用程序,這是我如何構建它,

第一觀點的文件。

file1.component.ts 
file1.component.html 

第二個視圖文件。

file2.component.ts 
file2.component.html 

所以每次我要創造我創建兩個新的文件,一個新的觀點。一個用於js邏輯,一個用於html視圖。

記住,每次創建新組件時都必須在app.module.ts文件和路由文件中註冊它。

app.module

//Layouts 
import { MyfileComponent }     from './views/myfile.component'; 

@NgModule({ 
    declarations: [ 
     AppComponent, 
     MyfileComponent 
    ], 
    imports: [ 
     BrowserModule, 
     routing 
    ], 
    providers: [ 
    Guard, 
    Auth, 
    {provide: LocationStrategy, useClass: HashLocationStrategy} 
    ], 
    bootstrap: [AppComponent] 
}) 
export class AppModule { 

} 

路線

const APP_ROUTES: Routes = [ 
    { path: '', redirectTo: '/home', pathMatch: 'full', }, 
    { path: 'home', component: MyfileComponent, data: { title: 'myfile View' } 
];