[英]How to use @Component decorator in both abstract class and in the implementation of abstract class in Angular 8?
我使用 Angular 8 并尝试使用抽象组件。 我想在我的抽象类中定义 templateUrl 和 styleUrls,但在实现的类中定义选择器名称。 像这样:
@Component({
// selector isn't defined here
templateUrl: './abstract-list.component.html',
styleUrls: ['./abstract-list.component.scss']
})
export abstract class AbstractListComponent<T> implements OnInit {
// ...
}
在儿童班
@Component({
selector: 'app-my-custom-list',
// templateUrl & styleUrls is should be inherited
})
export class MyCustomListComponent extends AbstractListComponent<MyCustomListInterface> implements OnInit {
// ...
}
我试图只在这样的实现中使用装饰器,但我觉得这里需要一个更好的方法:
@Component({
selector: 'app-my-custom-list',
templateUrl: '../../abstract-list/abstract-list.component.html',
styleUrls: ['../../abstract-list/abstract-list.component.scss']
})
是否可以使用这样的@Component
装饰器? 或者这种用法有什么技巧或最佳实践吗?
在@Rectangular的有用评论之后,我以这种方式开始:
在抽象类中:
export const componentDecoratorPreset = {
// selector isn't defined here
templateUrl: './abstract-list.component.html',
styleUrls: ['./abstract-list.component.scss']
};
export abstract class AbstractListComponent<T> implements OnInit {
// ...
}
然后在实现中:
import { AbstractListComponent, componentDecoratorPreset } from 'src/app/components/_absrtact/list/abstract-list.component';
@Component({
...componentDecoratorPreset,
selector: 'app-my-custom-list',
})
它当然不起作用,因为templateUrl
是相对的,并且在实现中./abstract-list.component.html
文件不存在。
下一步我只是尝试在抽象类中使用绝对路径,如下所示:
export const componentDecoratorPreset = {
// selector isn't defined here
templateUrl: 'src/app/components/_absrtact/list/abstract-list.component.html',
styleUrls: ['src/app/components/_absrtact/list/abstract-list.component.scss']
};
模板文件的相对路径或绝对 URL...
但路径不能是绝对的。 经过很少的搜索,我在主题中找到了这篇文章,这说明为什么路径不能是绝对的。 但我从这篇文章中得到了一个想法:
我创建了一个abstract-list.component.html.ts
- 扩展名是.ts
很重要 - 包含以下内容:
export default `<div class="container-fluid">...here is the abstract's template...</div>`
然后将此模板作为抽象类中的变量导入并作为对象导出:
import template from './abstract-list.component.html';
export const componentDecoratorPreset = {
// selector: must be defined in the implementation
template: template as string,
};
最后在实现中:
import { Component, OnInit } from '@angular/core';
import { AbstractListComponent, componentDecoratorPreset } from 'src/app/components/_absrtact/list/abstract-list.component';
import { AddressTypeInterface } from 'src/app/models/address/type/address-type.interface';
import { AddressType } from 'src/app/models/address/type/address-type.model';
@Component({
selector: 'app-address-type-list',
...componentDecoratorPreset
})
export class AddressTypeListComponent extends AbstractListComponent<AddressTypeInterface> implements OnInit {
constructor() {
super(AddressType);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.