元素包含无效元素(Angular 2+,RxJS)

时间:2019-07-02 14:36:25

标签: angular typescript dom rxjs

这是我的代码。 https://stackblitz.com/edit/angular-tq2vaa

converters

这是它在控制台中打印的内容。如您所见,app-editable-component包含h3,这是目标,但为什么ans为true?

cont

1 个答案:

答案 0 :(得分:2)

我尝试测试您的代码,请参见here

import { Component, ElementRef } from '@angular/core';
import  {fromEvent } from 'rxjs';
import { filter, take } from 'rxjs/operators';


@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {

constructor(private host: ElementRef) {
  this.editModeHandler();
}

get element() {
    return this.host.nativeElement;
}

private editModeHandler() {
      fromEvent(document, 'click')
      .pipe(
        filter(({ target }) => {
        console.log('parent', this.element, 'child', target)

          const ans = this.element.contains(target) === false
          console.log(ans)
          return  ans
        }),
        take(1)
     ).subscribe();
}  

}

当我单击<h3>标签ans时显示false!我和你在做同样的事吗?我想念什么吗?

enter image description here

更新

在您进行闪击之后,我看到发生了什么事。我将尝试变得简单:

  1. 您点击h3元素
  2. edit模式已激活(因此h3input取代了)
  3. 由于{click冒泡,document将返回contains(h3)(由于#2),因此false捕获到click事件。
  4. switchMapTo(clickOutside$)被执行
  5. view模式已激活(速度确实很高,因此您不会看到输入消失而消失)。

要解决此问题,可以在主机元素捕获传播后停止传播。

private viewModeHandler() {
        fromEvent(this.element, 'click').pipe(
            untilDestroyed(this)
        ).subscribe((e) => {
            console.log('clicked inside');
            this.editMode.next(true);
            this.mode = 'edit';
            e.stopPropagation();
        });
    }

希望这会有所帮助。