微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 没有视图的Angular 2组件

是否可以在不使用模板或@View的情况下使用Angular 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;
}
});

如果可能的话,我猜它会看起来像这样:

Angular 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.

我真的不喜欢将Jtml放在Javascript中,所以我希望有一些解决方法方法来做到这一点.

解决方法:

实际上,您应该像这样实现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,这意味着您希望使用ng-content为组件提供一些内容,这些内容可以包含在组件模板中.这是一个示例:Angular 2 Template Component.

希望它能帮到你,
蒂埃里

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐