html - 如何在 Angular 中处理自定义输入组件上的输入事件?
问题描述
我正在尝试使用 Reative Form 创建自定义输入组件,Angular 7
但我无法将事件传递给输入字段。
Mycomponent
有一个标签和一个输入字段以及一个特定的布局。我的component html
样子是这样的:
<div id="customInputGroup" [formGroup]="parentFormGroup" [ngClass]="{'input-value': hasValue()}">
<label [for]="inputId">{{label}}</label>
<input [id]="inputId" [name]="inputName" class="form-control" [placeholder]="placeholder" [formControlName]="inputName" [mask]="mask">
</div>
在我的Component
:
@Component({
selector: 'app-input-field',
templateUrl: './input-field.component.html',
styleUrls: ['./input-field.component.css']
})
export class InputFieldComponent implements OnInit {
@Input('placeholder') placeholder = '' ;
@Input('label') label = '';
@Input('inputId') inputId = '';
@Input('inputName') inputName = '';
@Input('parentFormGroup') parentFormGroup:FormGroup;
@Input('mask') mask;
constructor() { }
ngOnInit() {
}
hasValue(){
return (this.parentFormGroup.get(this.inputName).value != undefined
&& this.parentFormGroup.get(this.inputName).value != null
&& this.parentFormGroup.get(this.inputName).value != '')
}
一切正常,直到我不得不处理一个输入onBlur
事件(或者它可以是任何其他输入事件)。我想要的结果是调用我component
传递这样的任何事件:
<app-input-field (blur)="functionName()"></app-input-field>
或者
<app-input-field (keyup)="functionName()"></app-input-field>
我component
将能够“动态地”将这些事件传递给我的输入字段。有可能做到吗?
解决方案
像blur
作品这样的事件input field
,而不是像这样的选择器<app-input-field>
您可以为所有事件发出事件,如模糊、按键、鼠标悬停等。
输入字段组件:
HTML:
<input (blur)="functionName('blur')" (keyup)="functionName('keyUp')" [id]="inputId" [name]="inputName" class="form-control" [placeholder]="placeholder" [formControlName]="inputName" [mask]="mask">
TS:
@Output() OnInputEvent= new EventEmitter();
functionName(eventName) {
this.OnInputEvent.emit(eventName);
}
在您的组件中:
<app-input-field (OnInputEvent)="functionName($event)"></app-input-field>
TS:
functionName(event) {
switch (event) {
case "blur":
...
break;
case "keyUp":
...
break;
}
}
推荐阅读
- python - 如何在使用 tensorflow 时使用 logits 而不是概率来定义自定义损失函数
- reactjs - 如何在反应中将对象数组作为道具传递?
- java - 用 Java 读取 XML API 响应
- reactjs - 反应钩子形式渲染太多次
- python - 如何根据开始日期和结束日期之间的设定时间间隔来扩展带有额外行的 DataFrame?
- android - android studio 中的活动不显示任何内容,但也返回错误
- android - Android Studio 调试器中的 for 循环非常慢,没有它就快
- python - Python AST - 检测表达式中的非法标记
- php - WooCommerce 循环通过产品的自定义 post_meta
- office-ui-fabric - 如何在其他地方更改时重置 FluentUI 下拉选择?