英文:
typescript error: argument type is not assignable to parameter of type
问题
I will only provide the translation of the code section without the error message and additional content. Here's the translated code:
// app.component.ts 文件
import { Component, OnInit } from '@angular/core';
import {
FormBuilder,
FormGroup,
Validators,
AbstractControl,
ValidationErrors,
} from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./global_styles.css'],
})
export class AppComponent implements OnInit {
form!: FormGroup;
segmentValue = 'personal';
constructor(private formBuilder: FormBuilder) {}
ngOnInit() {
this.form = this.formBuilder.group({
firstName: [''],
lastName: [''],
businessName: [''],
});
this.form.setValidators([this.customValidator.bind(this)]);
}
customValidator(control: AbstractControl): ValidationErrors | null {
const formGroup = control as FormGroup;
const firstName = formGroup.get('firstName')!.value;
const lastName = formGroup.get('lastName')!.value;
const businessName = formGroup.get('businessName')!.value;
if (this.segmentValue === 'business' && !businessName) {
return { businessNameRequired: true };
}
if (this.segmentValue === 'personal' && (!firstName || !lastName)) {
return { namesRequired: true };
}
return null;
}
segmentChanged(event: CustomEvent) {
this.segmentValue = event.detail.value;
this.form.updateValueAndValidity(); // 触发段落更改时的验证
}
onSubmit() {
if (this.segmentValue === 'business') {
this.form.get('firstName')!.reset();
this.form.get('lastName')!.reset();
} else {
this.form.get('businessName')!.reset();
}
// 继续表单提交
console.log(this.form.value);
}
}
I have provided the translation of the TypeScript code. If you have any specific questions or need further assistance, please let me know.
英文:
I am trying to get rid of this erro message and trying to have my code work. My intention is to create an angular form validation consisting of firstName lastName businessName. If firstName and lastName are filled, businessName is no longer required and vice versa. If 'business' segment is selected, onSubmit, we need to clear firstName and lastName. If 'personal' is selected', onSubmit clear 'businessName'. My app.component.html gives this error in StackBlitz environment.
Argument of type 'Event' is not assignable to parameter of type 'CustomEvent<any>'.
Type 'Event' is missing the following properties from type 'CustomEvent<any>': detail, initCustomEvent
My segment is not in form but it's in the toolbar ion-segment. Here is a snippet and my code. Do I have any structural issues maybe? I can't tell maybe it is too simple. Help me out please.
Edit: Let me also provide you my development environment if it is appropriate stackblitz
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
//app.component.ts file
import { Component, OnInit } from '@angular/core';
import {
FormBuilder,
FormGroup,
Validators,
AbstractControl,
ValidationErrors,
} from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./global_styles.css'],
})
export class AppComponent implements OnInit {
form!: FormGroup;
segmentValue = 'personal';
constructor(private formBuilder: FormBuilder) {}
ngOnInit() {
this.form = this.formBuilder.group({
firstName: [''],
lastName: [''],
businessName: [''],
});
this.form.setValidators([this.customValidator.bind(this)]);
}
customValidator(control: AbstractControl): ValidationErrors | null {
const formGroup = control as FormGroup;
const firstName = formGroup.get('firstName')!.value;
const lastName = formGroup.get('lastName')!.value;
const businessName = formGroup.get('businessName')!.value;
if (this.segmentValue === 'business' && !businessName) {
return { businessNameRequired: true };
}
if (this.segmentValue === 'personal' && (!firstName || !lastName)) {
return { namesRequired: true };
}
return null;
}
segmentChanged(event: CustomEvent) {
this.segmentValue = event.detail.value;
this.form.updateValueAndValidity(); // To trigger validation when segment changes
}
onSubmit() {
if (this.segmentValue === 'business') {
this.form.get('firstName')!.reset();
this.form.get('lastName')!.reset();
} else {
this.form.get('businessName')!.reset();
}
// Proceed with form submission
console.log(this.form.value);
}
}
<!-- language: lang-html -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.10/angular.min.js"></script>
<?-- app.component.html file ?>
<ion-toolbar>
<ion-segment
[(ngModel)]="segmentValue"
(ionChange)="segmentChanged($event as CustomEvent)"
>
<ion-segment-button value="business"> Business </ion-segment-button>
<ion-segment-button value="personal"> Personal </ion-segment-button>
</ion-segment>
</ion-toolbar>
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<div *ngIf="segmentValue === 'personal'">
<label for="firstName">First Name:</label>
<input type="text" id="firstName" formControlName="firstName" />
<div
*ngIf="form.hasError('namesRequired') && form.get('firstName').touched"
>
First Name is required.
</div>
</div>
<div *ngIf="segmentValue === 'personal'">
<label for="lastName">Last Name:</label>
<input type="text" id="lastName" formControlName="lastName" />
<div *ngIf="form.hasError('namesRequired') && form.get('lastName').touched">
Last Name is required.
</div>
</div>
<div *ngIf="segmentValue === 'business'">
<label for="businessName">Business Name:</label>
<input type="text" id="businessName" formControlName="businessName" />
<div
*ngIf="
form.hasError('businessNameRequired') &&
form.get('businessName').touched
"
>
Business Name is required.
</div>
</div>
<button type="submit">Submit</button>
</form>
<!-- end snippet -->
答案1
得分: 1
如果您在您的Angular项目中启用了TypeScript的strict
模式,那么您无法传递segmentChanged(event: CustomEvent)
,因为它不被视为有效的EventListener实例。
修复此问题的一种方法是进行类型断言
segmentChanged(event: Event) {
this.segmentValue = (event as CustomEvent).detail.value;
this.form.updateValueAndValidity(); // 在分段更改时触发验证
}
英文:
If you have typescript strict
mode enabled in your angular project, then you can't pass segmentChanged(event: CustomEvent)
because It is not considered valid instance of EventListener.
One way to fix this issue by type assertion
segmentChanged(event: Event) {
this.segmentValue = (event as CustomEvent).detail.value;
this.form.updateValueAndValidity(); // To trigger validation when segment changes
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论