如何在Angular4中检测对父div而不对子div的聚焦?

时间:2019-05-13 07:47:25

标签: javascript html angular

我有一个自定义的自动填充元素。它由一个输入字段,一个按钮和一个包含自动完成功能的div组成。我想要的行为是,当我在输入框或下拉列表之外单击时,它会调用一个回调,该回调将保存输入字段中的内容,如果我单击一个下拉选择,则希望它调用选择我单击的对象并将其保存的事件。

但是当前不像预期的那样工作,当我单击下拉菜单时,将调用焦点提示,下拉菜单不会关闭,并且在第二次单击时实际上选择了下拉值。

这是组件:

    <div class="input-group input-group-sm " (focusout)="blur($event)">
  <input type="text" class="form-control" [ngModel]="userInput" title="{{userInput}}" (ngModelChange)="onValueChanged($event)"
    (focus)="$event.target.select()">
  <div>
    <button type="button" class="btn btn-secondary dropdown-toggle" (click)="showPredefinedOptions()">
    </button>
    <div *ngIf="showDropdown" [ngClass]="{'dropdown-menu dropdown-menu-right':true, 'show-address-autocomplete':showDropdown}">
      <div *ngIf="currentUserAddresses">
        <a *ngFor="let item of currentUserAddresses" class="dropdown-item ekat-dropdown-item" (click)="chooseAddress(item)">{{item}}</a>
        <div class="divider dropdown-divider"></div>
      </div>
      <a *ngFor="let item of currentResult" class="dropdown-item ekat-dropdown-item" (click)="chooseAddress(item)">{{item}}</a>
    </div>
  </div>
</div>

在ts文件中,我有一行@Output()focusOut:EventEmitter = new EventEmitter();定义我订阅的focusoutevent。

这是即时通讯的使用方式:

<td> <address-autocomplete [value]="product.defaultDeliveryAddress ? defaultAddress : product.deliveryAddress"  (onSelect)="onAddressChanged($event, product)"
                                 [userAddresses]="userAddressed" (onWritten)="onAddressWritten($event, product)" (focusOut)="focusOut(product)">></address-autocomplete></td>

为什么当我单击下拉列表元素时调用焦点聚焦?

1 个答案:

答案 0 :(得分:2)

为此更容易使用Angular's Reactive Forms

<input type="text" [formControl]="inputControl">

<select [formControl]="selectControl">
  <!-- ... -->
</select>
import { FormControl } from '@angular/forms';

export class MyComponent {
  inputControl = new FormControl(null, { updateOn: 'blur' });
  selectControl = new FormControl(null, { updateOn: 'change' });

  ngOnInit() {
    inputControl.valueChanges.subscribe(value => {
      // ...
    });
    selectControl.valueChanges.subscribe(value => {
      // ...
    });
  }
}