I want to change component's decorator from class in angular4 application.
Something like this:
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();
}
}
How can I implement this?
The decorator is not part of the class, so the this
inside the decorator doesn't refer to the component.
It would technically be possible to do so using static classes:
@Component({
selector: 'users',
templateUrl: UsersComponent.template,
styleUrls: ['./users.component.css']
})
export class UsersComponent {
users: any;
public static template: any = './users.component.html';
}
...but this would be completely useless, as a static value would just be the same as hardcoding it. Thankfully, Angular really doesn't require any variables to be used in decorators. It wouldn't work anyway; it compiles these templates behind the scenes with the components and changing the template would break the compiler (especially the AOT compiler).
Are you trying to change the html for a component? Using the Router
or structural directives is usually a better idea.
A more direct approach to switching out the template for a component would be to use a dynamic component that accesses other components' TemplateRef
s directly and can swap them out with the view.