我试图为自定义组件构建一个“字符计数器”角指令,而我不能使用ngModel来绑定该值。(下面显示的my-component非常复杂,因此,我请求您信任我,长期的目标是通过不同的组件使用相同的指令)。I必须在initialText输入属性设置为时拦截,当然,当changedText被触发时也必须拦截
<my-component
characterCount
[initialText]="value"
(changedText)="valueChange.emit($event)">
</my-component>
@Input() initialText;
@Output() changedText: EventEmitter<string> = new EventEmitter<string>();我已经想好了如何拦截changedText
@Directive({
selector: "[characterCount]",
})
...
@HostListener("changedText", ["$event"])
changeText(changedText){
this.setCharacterCount(changedText);
}但是我不知道在设置initialText属性时如何拦截。
谢谢你们的帮助。
发布于 2022-02-21 12:17:09
不久前,在这个所以中,有人问要向formControl添加一个最大长度
同样的想法
@Component({
selector: 'app-help',
template: `<p class="count-help">{{_text}}</p>`,
changeDetection: ChangeDetectionStrategy.OnPush,
styleUrls: ['./count.component.css']
})
export class CountComponent {
_text;
@Input() set text(value) {
if (value !== this._text) {
this._text = value;
this.cdr.detectChanges();
}
};
constructor(private cdr: ChangeDetectorRef) { }
}以及指令
@Directive({
selector: '[characterCount]',
})
export class CountLengthDirective implements OnInit,OnDestroy {
ref: ComponentRef<CountComponent>;
subscription: any;
constructor(
@Self() private control: NgControl,
private el: ElementRef,
private vcr: ViewContainerRef,
private resolver: ComponentFactoryResolver
) {}
ngOnInit() {
const factory = this.resolver.resolveComponentFactory(CountComponent);
this.ref = this.vcr.createComponent(factory);
this.subscription = this.control.valueChanges
.pipe(startWith(this.control.value))
.subscribe((res) => {
this.ref.instance.text =this.control.value.length+' characters'
});
}
ngOnDestroy() {
this.subscription && this.subscription.unsubscribe();
}在这一堆闪电战中
https://stackoverflow.com/questions/71205829
复制相似问题