如何在angular中装饰来自class的组件?

How to decorate component from class in angular?

我想在 angular4 应用程序中从 class 更改组件的装饰器。

像这样:

import { Component, OnInit } from '@angular/core';
import { BooksService } from './../books.service';

@Component({
  selector: 'users',
  templateUrl: this.template,
  styleUrls: ['./users.component.css']
})

export class UsersComponent {
  users: any;
  template: any = './users.component.html';

  constructor(private booksService : BooksService) {
    this.users = this.booksService.getItems();
  }
}

我该如何实现?

装饰器不是 class 的一部分,因此装饰器中的 this 不引用组件。

技术上可以使用静态 classes:

@Component({
  selector: 'users',
  templateUrl: UsersComponent.template,
  styleUrls: ['./users.component.css']
})

export class UsersComponent {
  users: any;
  public static template: any = './users.component.html';
}

...但这完全没用,因为静态值与硬编码一样。 值得庆幸的是,Angular 确实不需要在装饰器中使用任何变量。无论如何都行不通;它使用组件在幕后编译这些模板,更改模板会破坏编译器(尤其是 AOT 编译器)。

您要更改组件的 html 吗?使用 Router 或结构指令通常是更好的主意。

为组件切换模板的更直接方法是使用 dynamic component 直接访问其他组件的 TemplateRef 并可以将它们与视图交换。