我使用 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']
};
The relative path or absolute URL of a template file...
但是路径不可能是绝对的。经过一番搜索,我找到了 this article在主题中,为什么路径不能是绝对的是有道理的。但我从这篇文章中得到一个想法:
我创建了一个 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);
}
}
关于angular - 如何在 Angular 8 的抽象类和抽象类的实现中使用 @Component 装饰器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59585383/