[英]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.