没有视图的 Angular 2 组件

Angular 2 component without a view

本文关键字:组件 Angular 视图      更新时间:2023-09-26

是否可以在不使用模板或@View的情况下使用 Angular 2?

我正在寻找一种类似的方式,就像您在示例中所做的那样:

角度 1

索引.html

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

应用.js

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

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

角度 2

索引.html

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

应用程序

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

但不幸的是,我收到错误:

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

我不太喜欢把html放在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 模板组件。

希望对您有所帮助,蒂埃里