2016-01-29 96 views
3

有沒有可能使用Angular 2而不使用模板或@View?沒有視圖的角度2組件

角1

的index.html

<div ng-controller="appcontroller"> 
<div ng-class="{active: isActive()}"> 
    ..... 
</div> 
</div> 

app.js

angular.module('app', []).controller('appcontroller', function(){ 
$scope.isActive = function(){ 
    return true; 
} 
}); 

我正在尋找像你這樣的類似的方式做例子在以下

我猜測它看起來像這樣,如果它是可能的:

角2

的index.html

<app> 
<div [ngclass]="{active: isActive()}"> 
    ..... 
</div> 
</app> 

app.ts

import {Component} from 'angular2/core'; 
@Component({ 
selector: 'app' 
}) 
export class AppComponent { 
isActive(){ 
    return true; 
} 
} 

但不幸的是,我發現了錯誤:

... must have either 'template', 'templateUrl', or '@View' set. 

我真的不喜歡把HTML放在Javascript中,所以我希望有一些解決方法或方法來做到這一點。

回答

5

事實上,你應該實現AppComponent這樣的:

import {Component} from 'angular2/core'; 

@Component({ 
    selector: 'app' 
    template: ` 
    <div [ngClass]="{active: isActive()}"> 
     ..... 
    </div> 
    ` 
}) 
export class AppComponent { 
    isActive(){ 
    return true; 
    } 
} 

或使用templateUrl屬性:

import {Component} from 'angular2/core'; 

@Component({ 
    selector: 'app' 
    templateUrl: 'component.html' 
}) 
export class AppComponent { 
    isActive(){ 
    return true; 
    } 
} 

和使用這樣的組件:

<app></app> 

如果你在app標籤裏放了一些HTML,這意味着y您想使用ng-content向組件模板中提供的組件模板提供一些內容。以下是一個示例:Angular 2 Template Component

希望它可以幫助你, 蒂埃裏

+0

所以沒有其他辦法,然後放了打字稿文件本身的HTML(無論是在代碼或html的文件)? –

+0

您可以使用'templateUrl'屬性來引用包含視圖內容的HTML文件...我更新了我的答案。 –

+0

嗯,我用你的上面的建議,並使用templateUrl,並最終能夠得到Angular 2應用程序運行。 再次感謝Thierry! –