typescript错误:参数类型不能赋值给类型的参数

huangapple go评论80阅读模式
英文:

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 &#39;@angular/core&#39;;
import {
FormBuilder,
FormGroup,
Validators,
AbstractControl,
ValidationErrors,
} from &#39;@angular/forms&#39;;
@Component({
selector: &#39;my-app&#39;,
templateUrl: &#39;./app.component.html&#39;,
styleUrls: [&#39;./global_styles.css&#39;],
})
export class AppComponent implements OnInit {
form!: FormGroup;
segmentValue = &#39;personal&#39;;
constructor(private formBuilder: FormBuilder) {}
ngOnInit() {
this.form = this.formBuilder.group({
firstName: [&#39;&#39;],
lastName: [&#39;&#39;],
businessName: [&#39;&#39;],
});
this.form.setValidators([this.customValidator.bind(this)]);
}
customValidator(control: AbstractControl): ValidationErrors | null {
const formGroup = control as FormGroup;
const firstName = formGroup.get(&#39;firstName&#39;)!.value;
const lastName = formGroup.get(&#39;lastName&#39;)!.value;
const businessName = formGroup.get(&#39;businessName&#39;)!.value;
if (this.segmentValue === &#39;business&#39; &amp;&amp; !businessName) {
return { businessNameRequired: true };
}
if (this.segmentValue === &#39;personal&#39; &amp;&amp; (!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 === &#39;business&#39;) {
this.form.get(&#39;firstName&#39;)!.reset();
this.form.get(&#39;lastName&#39;)!.reset();
} else {
this.form.get(&#39;businessName&#39;)!.reset();
}
// Proceed with form submission
console.log(this.form.value);
}
}

<!-- language: lang-html -->

&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.10/angular.min.js&quot;&gt;&lt;/script&gt;
&lt;?-- app.component.html file ?&gt;
&lt;ion-toolbar&gt;
&lt;ion-segment
[(ngModel)]=&quot;segmentValue&quot;
(ionChange)=&quot;segmentChanged($event as CustomEvent)&quot;
&gt;
&lt;ion-segment-button value=&quot;business&quot;&gt; Business &lt;/ion-segment-button&gt;
&lt;ion-segment-button value=&quot;personal&quot;&gt; Personal &lt;/ion-segment-button&gt;
&lt;/ion-segment&gt;
&lt;/ion-toolbar&gt;
&lt;form [formGroup]=&quot;form&quot; (ngSubmit)=&quot;onSubmit()&quot;&gt;
&lt;div *ngIf=&quot;segmentValue === &#39;personal&#39;&quot;&gt;
&lt;label for=&quot;firstName&quot;&gt;First Name:&lt;/label&gt;
&lt;input type=&quot;text&quot; id=&quot;firstName&quot; formControlName=&quot;firstName&quot; /&gt;
&lt;div
*ngIf=&quot;form.hasError(&#39;namesRequired&#39;) &amp;&amp; form.get(&#39;firstName&#39;).touched&quot;
&gt;
First Name is required.
&lt;/div&gt;
&lt;/div&gt;
&lt;div *ngIf=&quot;segmentValue === &#39;personal&#39;&quot;&gt;
&lt;label for=&quot;lastName&quot;&gt;Last Name:&lt;/label&gt;
&lt;input type=&quot;text&quot; id=&quot;lastName&quot; formControlName=&quot;lastName&quot; /&gt;
&lt;div *ngIf=&quot;form.hasError(&#39;namesRequired&#39;) &amp;&amp; form.get(&#39;lastName&#39;).touched&quot;&gt;
Last Name is required.
&lt;/div&gt;
&lt;/div&gt;
&lt;div *ngIf=&quot;segmentValue === &#39;business&#39;&quot;&gt;
&lt;label for=&quot;businessName&quot;&gt;Business Name:&lt;/label&gt;
&lt;input type=&quot;text&quot; id=&quot;businessName&quot; formControlName=&quot;businessName&quot; /&gt;
&lt;div
*ngIf=&quot;
form.hasError(&#39;businessNameRequired&#39;) &amp;&amp;
form.get(&#39;businessName&#39;).touched
&quot;
&gt;
Business Name is required.
&lt;/div&gt;
&lt;/div&gt;
&lt;button type=&quot;submit&quot;&gt;Submit&lt;/button&gt;
&lt;/form&gt;

<!-- 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
}

huangapple
  • 本文由 发表于 2023年7月6日 20:13:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76628713.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定