我有一个组件
@Component({
// todo the app-old-selector selector must be removed in the next version
selector: 'app-new-selector,app-old-selector',
templateUrl: './component.html'
})
export class Component {
}
通知开发人员app-old-selector
已过时的最佳方法是什么?
答案 0 :(得分:2)
可能您可以在组件代码中编写如下代码:
import { Component, ElementRef } from '@angular/core'
@Component({
selector: 'app-new-selector,app-old-selector',
templateUrl: './component.html'
})
export class YourComponent {
constructor(elem: ElementRef) {
const tagName = elem.nativeElement.tagName.toLowerCase();
if (tagName === 'app-old-selector') {
console.warn('message');
}
}
}
这意味着我们只需将当前启动的组件的标签名称与代表不赞成使用的值的字符串进行比较。如果它们相等,则意味着您现在需要通知开发人员。
这里是工作中的Stackblitz example。随时在打开控制台的情况下运行它。
答案 1 :(得分:1)
据我所知,没有内置的方法可以做到这一点。但是,您可以尝试使用ElementRef
功能提醒开发人员:
import { Component, ElementRef } from '@angular/core'
@Component({
selector: 'app-new-selector,app-old-selector',
templateUrl: './component.html'
})
export class MyComponent {
constructor(elem: ElementRef) {
if (elem.nativeElement.tagName.toLowerCase() === 'app-old-selector') {
console.warn(`'app-old-selector' selector is deprecated; use 'app-new-selector' instead.`);
}
}
}
或者,如果您需要此功能可重用并且想要确保整个库的一致性,则可以提供可注入的服务,如下所示:
import { Injectable } from '@angular/core';
@Injectable()
export class Deprecator {
warnDeprecatedSelector(elem: ElementRef, oldSelector: string, newSelector: string) {
if (elem.nativeElement.tagName.toLowerCase() === oldSelector) {
console.warn(`'${oldSelector}' selector is deprecated; use '${newSelector}' instead.`);
}
}
}
import { Component, ElementRef } from '@angular/core'
@Component({
selector: 'app-new-selector,app-old-selector',
templateUrl: './component.html'
})
export class MyComponent {
constructor(elem: ElementRef, deprecator: Deprecator) {
deprecator.warnDeprecatedSelector(elem, 'app-old-selector', 'app-new-selector');
}
}
答案 2 :(得分:1)
我写了一个可重用的装饰器,将组件的选择器标记为已弃用。
import {Component} from '@angular/core';
type Constructor<T = {}> = new (...args: any[]) => T;
export function Deprecated(oldSelector: string) { // This is a decorator factory
return <T extends Constructor>(Base: T) => {
return class Deprecated extends Base {
selectors = [];
constructor(...args: any[]) {
super(...args);
const selector = new Component((Deprecated as any).__annotations__[0]).selector;
this.selectors = selector.split(', ');
this.selectors = this.selectors.filter(selector => selector !== oldSelector);
console.warn('The selector "' + oldSelector + '" is going to be deprecated. Please use one of these selectors [ ' + this.selectors.toString() + ' ]');
}
};
};
}
现在我们只需要使用此装饰器函数(如下所示的参数)装饰组件类
@Component({
selector: 'my-old-app, my-app-new',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
@Deprecated("my-old-app")
export class AppComponent {
name = 'Angular';
}
请在stackblitz中找到代码here。
另外,请阅读我的blog,该主题有关于逻辑的解释。