【问题标题】:How to decorate component from class in angular?如何以角度装饰类中的组件?
【发布时间】:2017-10-17 12:44:24
【问题描述】:

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

类似这样的:

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();
  }
}

我该如何实现呢?

【问题讨论】:

标签: javascript angular typescript angular-components angular-decorator


【解决方案1】:

装饰器不是类的一部分,所以装饰器内的this 不引用组件。

技术上可以使用静态类来做到这一点:

@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 直接访问其他组件的TemplateRefs 并可以将它们与视图交换。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-06
    • 1970-01-01
    • 2014-04-24
    • 1970-01-01
    • 1970-01-01
    • 2019-10-02
    • 1970-01-01
    • 2017-12-29
    相关资源
    最近更新 更多