![](/img/trans.png)
[英]Angular2 — @ViewChild from TypeScript base abstract class
[英]Angular 9 decorators on abstract base class
我正在将我的项目从 Angular 8 升级到 9,并且在扩展类时遇到了新要求的问题。
根据 Angular 的 文档:
使用 Angular 功能的未修饰基类
从版本 9 开始,不推荐使用未修饰的基础 class :
- 使用 Angular 特性
- 由指令或组件扩展
Angular 生命周期钩子或以下任何 Angular 字段装饰器被视为 Angular 功能:
@Input()
@Output()
@HostBinding()
@HostListener()
@ViewChild()
/@ViewChildren()
@ContentChild()
/@ContentChildren()
对于@Component
装饰器,它需要基于 class 的template
或templateURL
。 添加任何一个都会导致子 class 不呈现它的模板。
例如,以下结果不会在视图上呈现任何内容:
@Component({
template: ''
})
export abstract class BaseComponent<T extends AbstractSuperEntity> extends Toggler implements OnChanges {
@Input()
year: number | string
constructor(service: MyService) {
}
ngOnChanges() {
}
}
@Component({
templateUrl: 'my.component.html',
selector: 'my-component'
})
export class MyComponent extends BaseComponent<AbstractSuperEntity> {
constructor(service: MyService) {
super(service);
}
}
我尝试更改基础 class 以使用指向空 html 的templateUrl
,但这也不起作用。
您必须添加一个空的@Directive()
装饰器。 据我所知,这应该足够了:
@Directive()
export abstract class BaseComponent<T extends AbstractSuperEntity> extends Toggler implements OnChanges {
@Input()
year: number | string
constructor(service: MyService) {
}
ngOnChanges() {
}
}
问这个问题已经有一段时间了,但我偶然发现了它,所以这可能对其他人也有用。
您不一定要添加 @Directive 装饰器。 如果它是一个组件,只需使用 @Component 代替。 那应该行得通。 请参阅以下 stackblitz 示例:
https://stackblitz.com/edit/angular-ivy-kehmwu?file=src/app/app.component.ts
在这个问题中,目前还不清楚出了什么问题。 一条错误消息会有所帮助。
还可能出错的是 OP 没有在 super 调用上实现生命周期方法:
import { Component, OnInit, Input } from '@angular/core';
@Component({
template: '',
})
export abstract class BaseComponent implements OnInit {
@Input()
year: number | string;
constructor() {}
ngOnInit() {
console.log('This will only work if you call it in the child component');
}
}
@Component({
selector: 'child-component',
template: '<p>test, year: {{ year }}</p>',
})
export class ChildComponent extends BaseComponent implements OnInit {
constructor() {
super();
}
ngOnInit() {
super.ngOnInit();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.