yavg
yavg

Reputation: 3051

detect when a child component is clicked outside

I have a child component called: mycomponent with this code:

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>

I am calling it in app.ts:

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

in 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;
}
}

when I click on the input of mycomponent a div is displayed.

How can I make the div disappear when I click outside of it, except when I click on the same input?

enter image description here

this is my live code:

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

Upvotes: 1

Views: 372

Answers (2)

Nav Kumar V
Nav Kumar V

Reputation: 350

Use stopPropagation event

app.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>

app.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();
 }
}

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

Upvotes: 1

fbfatboy
fbfatboy

Reputation: 401

Consider listening on focus and blur events I have changed your code

anthor idea

Upvotes: 0

Related Questions