Директива работает для каждого экземпляра связанных компонентов? - PullRequest
0 голосов
/ 29 января 2020

У меня есть директива, которая используется несколькими экземплярами одного и того же компонента (например: поля ввода в форме). Но если я использую один экземпляр, функциональность директивы запускается для каждого экземпляра, присутствующего в текущем родительском компоненте.

Как вы можете убедиться, что ваша директива работает только для необходимого экземпляра?

IF это какая-то ошибка / логика c ошибка на моей стороне, как я могу от нее избавиться?

Исключения - это объект массивов, содержащий атрибуты для пропуска, если они существуют на цели, он пропускается, иначе выдает автосохранение событие.

@ Редактировать:

@Directive({
  selector: '[InlineAutosave]'
})
export class AutosaveDirective implements OnInit, OnChanges, OnDestroy {

  readonly inlineDefaultExceptions: AutoSaveExceptions = {
    roles: [],
    classes: ['c-inline-editor',
      'form-control custom-inline-editor ng-untouched ng-pristine ng-valid',
      'form-control custom-inline-editor ng-pristine ng-valid ng-touched',
      'editable-empty c-inline-editor',
      'form-control w-100 mb-2 ng-untouched ng-pristine ng-valid',
      'form-control w-100 mb-2 ng-pristine ng-valid ng-touched'],
    ids: ['inline-editor-save', 'inline-editor-cancel', 'pencilIcon']
  };

  private exceptionAttributes: AutoSaveExceptions;
  clicks$ = new Subject<HTMLElement>();
  changes$ = new BehaviorSubject<AutoSaveExceptions>(this.inlineDefaultExceptions);
  changeSub$: Subscription;
  clickSub$: Subscription;



  @Input() exceptions: AutoSaveExceptions;
  @Output() autosave = new EventEmitter();

  constructor(private elementRef: ElementRef) { }

  ngOnInit() {
    this.exceptionAttributes = this.inlineDefaultExceptions;
    this.changeSub$ = this.changes$.subscribe(exceptionObj => this.exceptionAttributes = exceptionObj);
    this.clickSub$ = this.clicks$.subscribe(target => this.handleClicks(target));
  }

  ngOnChanges(changes: SimpleChanges) {
    if (changes && changes['exceptions'] && changes['exceptions'].firstChange === true) {
      this.changes$.next(changes['exceptions'].currentValue);
    }
  }

  ngOnDestroy() {
    this.changeSub$.unsubscribe();
    this.clickSub$.unsubscribe();
  }

  @HostListener('document:click', ['$event.target'])
  onClick(target: HTMLElement) {
    this.clicks$.next(target);
  }

  private handleClicks(target: HTMLElement) {
    if (target.hasAttribute('id')) {
      if (target.attributes.getNamedItem('id').value !== undefined) {
        const targetId = target.attributes.getNamedItem('id').value;
        if (this.exceptionAttributes.ids.indexOf(targetId) < 0) {
          console.log('autosave ID');
          this.autosave.emit();
        }
      }
    } else if (target.hasAttribute('class')) {
      if (target.attributes.getNamedItem('class').value !== undefined) {
        const targetClass = target.attributes.getNamedItem('class').value;
        if (this.exceptionAttributes.classes.indexOf(targetClass) < 0) {
          console.log('autosave CLASS');
          this.autosave.emit();
        }
      }
    } else if (target.hasAttribute('role')) {
      if (target.attributes.getNamedItem('role').value !== undefined) {
        const targetRole = target.attributes.getNamedItem('role').value;
        if (this.exceptionAttributes.roles.indexOf(targetRole) < 0) {
          console.log('autosave ROLE');
          this.autosave.emit();
        }
      }
    } else if (target === this.elementRef.nativeElement) {
    }
  }

}
...