gpt4 book ai didi

Angular - 如何将管道注入(inject)指令

转载 作者:行者123 更新时间:2023-12-02 00:29:47 26 4
gpt4 key购买 nike

我已经设置了一个指令,它根据您作为参数传递的管道 (@Input) 为输入值提供格式。我将它用于 react 形式。

为此,我需要导入所有需要的管道(目前只有一个),并提供一个开关以使用正确的管道。

我的问题是:有没有一种方法可以从只知道其标记的注入(inject)器获取任何管道,如 const pipe = injector.get('currency');

这是我的指令代码:

import { Input, Renderer2, ElementRef, forwardRef, Directive, HostListener } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { CurrencyPipe } from '@angular/common';

@Directive({
selector: '[formatInput]',
providers: [
{ provide: NG_VALUE_ACCESSOR, multi: true, useExisting: forwardRef(() => FormatInputDirective) },
],
})
export class FormatInputDirective implements ControlValueAccessor {
private changeCallback: Function;
private touchedCallback: Function;

@Input() pipe: any; // { token: string, args: any[] }

@HostListener('input', ['$event.target.value'])
onChange(value) {
this.changeCallback(value);
}

@HostListener('blur', ['$event.target'])
onBlur(target) {
this.touchedCallback();
}

constructor(private renderer: Renderer2, private currency: CurrencyPipe, private elRef: ElementRef ) {
this.changeCallback = (_: any) => {};
this.touchedCallback = () => {};
}

writeValue(value: any): void {
this.renderer.setProperty(this.elRef.nativeElement, 'value', this.setPipedValue(value));
}

setPipedValue(value: any): any {
if (!this.pipe || !value) {
return value;
} else {
let pipe;

switch (this.pipe.token) {
case 'currency':
pipe = this.currency;
break;
}
return pipe.transform(value, ...this.pipe.args);
}
}

registerOnChange(fn) {
this.changeCallback = fn;
}

registerOnTouched(fn: any): void {
this.touchedCallback = fn;
}
}

预先感谢您的回复。

最佳答案

与注入(inject)一样,您首先必须提供您想要使用的东西。在相应的 NgModule 中,将 CurrencyPipe(以及您稍后要注入(inject)的所有其他内容)添加到 providers 数组。

providers: [CurrencyPipe],

现在注入(inject) Injector,将其添加到指令的构造函数中。

constructor (private injector: Injector)

通过使用 get 方法和 token 作为参数,使用它来获取您想要的管道实例。在这种情况下, token 就是类本身。

const pipe = injector.get(CurrencyPipe)

现在你有了一个管道实例。您可以使用它的 transform 方法来执行转换。

this.value = pipe.transform(123456789)

你可以 see this in action on StackBlitz

请注意,Angular 没有使用字符串进行依赖注入(inject)的概念。您可以改用 token ,但是在管道的情况下,这并不能使您对已有的类拥有太多的权力。

如果要将管道指定为字符串,则必须自己定义映射。

const MAP = { 'currency': CurrencyPipe, 'decimal': DecimalPipe }

现在使用此映射生成正确管道的实例。

const pipeName = 'currency'
const pipeClass = MAP[pipeName]
const pipe = injector.get(pipeClass)
const value = pipe.transform(input)

关于Angular - 如何将管道注入(inject)指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52343556/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com