首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >角12 -指令中组件的字符反绑定属性输入初始化

角12 -指令中组件的字符反绑定属性输入初始化
EN

Stack Overflow用户
提问于 2022-02-21 11:49:04
回答 1查看 22关注 0票数 0

我试图为自定义组件构建一个“字符计数器”角指令,而我不能使用ngModel来绑定该值。(下面显示的my-component非常复杂,因此,我请求您信任我,长期的目标是通过不同的组件使用相同的指令)。I必须在initialText输入属性设置为时拦截,当然,当changedText被触发时也必须拦截

代码语言:javascript
复制
<my-component
      characterCount
      [initialText]="value"
      (changedText)="valueChange.emit($event)">
</my-component>

  @Input() initialText;
  @Output() changedText: EventEmitter<string> = new EventEmitter<string>();

我已经想好了如何拦截changedText

代码语言:javascript
复制
@Directive({
  selector: "[characterCount]",
})
...
  @HostListener("changedText", ["$event"])
  changeText(changedText){
    this.setCharacterCount(changedText);
  }

但是我不知道在设置initialText属性时如何拦截。

谢谢你们的帮助。

EN

回答 1

Stack Overflow用户

发布于 2022-02-21 12:17:09

不久前,在这个所以中,有人问要向formControl添加一个最大长度

同样的想法

代码语言:javascript
复制
@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) { }

}

以及指令

代码语言:javascript
复制
@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();
  }

这一堆闪电战

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71205829

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档