在属性上使用@input和@output装饰器时,我得到一个事件对象以及在输出属性上传递对象,并且一个事件对象复制传递的对象。
这是我的代码。
在Parent组件中。
<example [focusOn]="focusOnExample" (change)="checkExampleData($event)"></example>
checkExampleData(example: any){
this.starSign = example;
}
我的孩子成分是
<input type="checkbox" class="custom-control-input" (click)="isExampleClicked($event.target.checked)">
<input type="text" #myInput class="form-control" style="text-transform: uppercase" formControlName="exxampleNo" [readonly]="!showHide"
(keyup)="formResponse(myForm)">
@Component({
selector: 'example ',
templateUrl: './child.html',
styleUrls: ['./child.css']
})
export class ExampleComponent implements OnInit {
public myForm: FormGroup;
public showHide: boolean = true;
public exampleData = {
exampleValue: "",
exampleValid: false
}
@Input() focusOn: boolean;
@Output() change: EventEmitter<any> = new EventEmitter<any>();
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.addValidationOnExample();
}
addValidationOnExample() {
this.exampleData .exampleValid = false;
this.myForm = this.fb.group({
panNo: ['', [Validators.required, Validators.maxLength(10), Validators.minLength(10)]]
});
this.sendOutput(this.exampleData)
}
removeValidation() {
this.exampleData.exampleValid = true;
this.myForm = this.fb.group({
panNo: []
});
this.sendOutput(this.exampleData);
}
isExampleClicked(value: boolean) {
this.exampleData.exampleValue = "";
if (value) {
this.showHide = false;
this.removeValidation();
} else {
this.showHidePan = true;
this.addValidationOnExample();
}
}
formResponse(formData: any) {
if (formData.valid) {
this.exampleData.exampleValue = formData.value.exxampleNo;
this.exampleData.exampleValid = formData.valid;
this.sendOutput(this.exampleData)
}else{
this.exampleData.exampleValue = "";
this.exampleData.exampleValid = formData.valid;
this.sendOutput(this.exampleData)
}
}
sendOutput(exampleData){
this.change.emit(exampleData);
}
}
当我检查父组件中的checkExampleData函数时,我在这里得到两个对象(传递对象和事件对象)。这也会将this.starSign值作为事件对象而不是exampleData发出。
之所以发生这种情况,是因为您使用了名称change
,默认情况下由angular为变更事件定义。
您必须使用其他名称而不是change
。
像这样使用event.target.value
checkExampleData(example: any){
this.starSign = example.target.value;
console.log("value",this.starSign);
}
这就是你得到的所有数据。每当使用事件时,您必须使用event.target.value。
试一试,让我知道。