首页 > 解决方案 > 检测何时在外部单击子组件

问题描述

我有一个名为:mycomponent使用此代码的子组件:

import { Component,Input } from "@angular/core";
@Component({
  selector: "mycomponent",
  templateUrl: "./mycomponent.html"
})
export class MyComponent {
  @Input() myArray: any;
  @Input() index: any;
  @Input() indexSelected: any;
  constructor() {
  }
}
<input type="text" (click)="bShow=true" >{{myArray}}
<div style="border:1px solid red; width:200px; height:50px;" *ngIf="indexSelected==index">
  data: {{myArray}}
  <br>
  <button (click)="indexSelected=null">close</button>
</div>

我在 app.ts 中调用它:

<ng-container *ngFor="let item of myArray">
  <mycomponent [myArray]="item"></mycomponent>
  <br>
</ng-container>

在 app.ts 中

<ng-container *ngFor="let item of myArray; let i=index" >
  <mycomponent (click)="fn_selectIndex(i)" [myArray]="item" [indexSelected]="indexSelected"  [index]="i"></mycomponent>
<br>
</ng-container>

export class AppComponent  {
  name = 'Angular';
  myArray:any=[1,2,3,4,5];
  indexSelected=null;

fn_selectIndex(i:any){ 
  this.indexSelected=i;
}
}

当我点击ainput时显示。mycomponentdiv

当我点击它外部时,我怎样才能使它div消失,除非我点击它input

在此处输入图像描述

这是我的实时代码:

https://stackblitz.com/edit/angular-atr1zm?file=src%2Fapp%2Fmycomponent.html

标签: angular

解决方案


使用stopPropagation事件

应用程序.html

<div (click)="fn_selectIndex($event, -1)" style="height:100vh">
  <ng-container *ngFor="let item of myArray; let i=index" >
    <mycomponent (click)="fn_selectIndex($event, i)" [myArray]="item" [indexSelected]="indexSelected"  [index]="i"></mycomponent>
  <br>
  </ng-container>
</div>

应用程序.ts

export class AppComponent  {
  name = 'Angular';
  myArray:any=[1,2,3,4,5];
  indexSelected=null;s

 fn_selectIndex(event, i:any){
   this.indexSelected=i;
   event.stopPropagation();
 }
}

参考:https ://stackblitz.com/edit/angular-edld9f?file=src/app/app.component.ts


推荐阅读