angular - 检测何时在外部单击子组件
问题描述
我有一个名为: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
时显示。mycomponent
div
当我点击它外部时,我怎样才能使它div
消失,除非我点击它input
?
这是我的实时代码:
https://stackblitz.com/edit/angular-atr1zm?file=src%2Fapp%2Fmycomponent.html
解决方案
使用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
推荐阅读
- html - 单击按钮后显示或隐藏内容的代码
- python - 我的蜘蛛怎么了?它在几秒钟内开始和结束,创建一个空文件
- amazon-web-services - AWS Lambda/DynamoDB
- c# - Qlik Desktop - 自定义连接器 - ExtractQuery 和其他问题上的错误
- sql - 集团历史数据
- android - 任务:app:bundleReleaseJsAndAssets 失败 - React Native - Android
- multinomial - 多项 logit 模型的 dimnames(x) 错误
- c# - EF 6.4 单元测试对框架运行正常,但 dotnet 5.0 找不到我的连接字符串
- powershell - 将文件夹/子中的所有最新文件复制到powershell中的同名文件夹/子中
- excel-formula - Excel动态数组公式创建列的运行积