简体   繁体   English

Angular - 对象可能为“null”:错误 TS7052:元素隐式具有“any”类型,因为类型“AbstractControl”

[英]Angular - Object is possibly 'null': error TS7052: Element implicitly has an 'any' type because type 'AbstractControl'

In my Angular-12 code I have this component:在我的 Angular-12 代码中,我有这个组件:

component:成分:

export class AchievementFormComponent implements OnInit {
  data!: ICandidate;
  @Input() achievementDetailsForm!: FormGroup;
  constructor(
    private fb: FormBuilder,
    private candidateService: CandidateService
  ) { }

  ngOnInit(): void {
    this.achievementDetailsForm = this.fb.group({
      achievements: this.fb.array([this.createAchievementFormGroup()]),
    });
  }

  public addAchievementFormGroup() {
    const achievements = this.achievementDetailsForm.get('achievements') as FormArray;
    achievements.push(this.createAchievementFormGroup());
  }

  public removeOrClearAchievement(i: number) {
    const achievements = this.achievementDetailsForm.get('achievements') as FormArray;
    if (achievements.length > 1) {
      achievements.removeAt(i);
    } else {
      achievements.reset();
    }
  }

  private createAchievementFormGroup(): FormGroup {
    return new FormGroup({
      institution: new FormControl(''),
      degree: new FormControl(''),
      startDate: new FormControl(''),
      endDate: new FormControl(''),
      description: new FormControl(''),
      percentage: new FormControl(''),
    });
  }

  addAchievementDetails() {
    if (this.achievementDetailsForm.dirty) {
      this.data = this.candidateService.getCandidateDetails();
      this.data.achievement = this.achievementDetailsForm.value.achievements;
      this.candidateService.setCandidateDetails(this.data);
    }
  }
}

html: html:

 <form [formGroup]="achievementDetailsForm"> <div class="row"> <div class="col-md-12 col-lg-12 mb-4 align-items-stretch"> <div class="card border-0 rounded-0 h-100"> <div class="card-title mb-1 p-3"> <h5>Achievement Details:</h5> </div> <div class="card-body"> <div formArrayName="achievements"> <div *ngFor="let achievement of achievementDetailsForm.get('achievements')['controls']; let i = index" [formGroupName]="i"> <div class="form-group row"> <label for="institution" class="col-sm-2 col-form-label text-nowrap">Institute Name:</label> <div class="col-xs-4"> <input type="text" id='institution' maxlength="20" onkeypress='return ((event.charCode >= 65 && event.charCode <= 90) || (event.charCode >= 97 && event.charCode <= 122) || (event.charCode == 32))' class="form-control" placeholder="Enter your institution name" formControlName="institution" required> </div>&nbsp;&nbsp;&nbsp; <label for="degree" class="col-sm-2 col-form-label text-nowrap">Board/ Degree:</label> <div class="col-xs-4"> <input class="form-control" id="degree" placeholder="Enter your degree/degree" type="text" onkeypress='return ((event.charCode >= 65 && event.charCode <= 90) || (event.charCode >= 97 && event.charCode <= 122) || (event.charCode == 32))' formControlName="degree" required> </div> <div class="col-xs-4"> <button class="float-left" mat-icon-button color="primary" aria-label="Add" (click)="addAchievementFormGroup()" matTooltip="Add"> <mat-icon>add_circle_outline</mat-icon> </button> <button class="float-left" mat-icon-button color="primary" aria-label="Remove/clear" (click)="removeOrClearAchievement(i)" matTooltip="Remove"> <mat-icon>highlight_off</mat-icon> </button> </div> </div> <div class="form-group row"> <label for="description" class="col-sm-2 col-form-label text-nowrap">Stream:</label> <div class="col-xs-4"> <input type="text" id='description' maxlength="15" onkeypress='return ((event.charCode >= 65 && event.charCode <= 90) || (event.charCode >= 97 && event.charCode <= 122) || (event.charCode == 32))' class="form-control" placeholder="Enter your stream/major" formControlName="description" required> </div>&nbsp;&nbsp;&nbsp; <label for="startDate" class="col-sm-2 col-form-label text-nowrap">Starting date:</label> <div class="col-xs-4"> <input type="date" id="startDate" class="form-control" placeholder="dd-mm-yyyy" value="" formControlName="startDate" required> </div> </div> <div class="form-group row"> <label for="zipcode" class="col-sm-2 col-form-label text-nowrap">Percentage(%):</label> <div class="col-xs-4"> <input type="text" class="form-control" id="percentage" placeholder="Enter your percentage" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\\..*)\\./g, '$1');" maxlength="3" formControlName="percentage" required> </div>&nbsp;&nbsp;&nbsp; <label for="endDate" class="col-sm-2 col-form-label text-nowrap">Ending date:</label> <div class="col-xs-4"> <input type="date" id="endDate" class="form-control" placeholder="dd-mm-yyyy" value="" formControlName="endDate" required> </div> </div> <hr /> </div> </div> </div> </div> </div> </div> <div> <button mat-button matStepperPrevious>Back</button> <button mat-button matStepperNext (click)="addAchievementDetails()">Next</button> </div> </form>

Instead of the form to load, I got this error:我收到了这个错误,而不是要加载的表单:

error TS2531: Object is possibly 'null'错误 TS2531:对象可能为“空”

error TS7052: Element implicitly has an 'any' type because type 'AbstractControl' has no index signature.错误 TS7052:元素隐式具有“any”类型,因为“AbstractControl”类型没有索引签名。 Did you mean to call 'get'?你的意思是叫'get'吗?

and this line is highlighted:这一行突出显示:

achievementDetailsForm.get('achievements')['controls'];成就详细信息Form.get('成就')['控制'];

in

How do I resolve this?我该如何解决?

Thanks谢谢

The problem is that achievementDetailsForm.get('achievements') returns an AbstractControl instance, so in template, the compiler won't be able to know that it's a FormArray instance and thus it doesn't know that it has the controls property.问题是achievementDetailsForm.get('achievements')返回一个AbstractControl实例,因此在模板中,编译器将无法知道它是一个FormArray实例,因此它不知道它具有controls属性。

To solve this problem, you could either create a getter that returns the FormArray instance or (preferably IMHO) store the FormArray in a variable (let's call it achievementsFormArray ) and then you can use this in template (and also within TS file):为了解决这个问题,你既可以创建一个getter,返回FormArray实例或(最好恕我直言)存储FormArray在一个变量(让我们称之为achievementsFormArray ),然后就可以在模板中使用这个(和内TS文件):

TS : TS :

export class AchievementFormComponent implements OnInit {
  data!: ICandidate;
  @Input() achievementDetailsForm!: FormGroup;
  readonly achievementsFormArray!: FormArray;

  constructor(
    private fb: FormBuilder,
    private candidateService: CandidateService,
  ) {}
    
  ngOnInit(): void {
    // Note that you could also initialize these properties directly in the declaration and then remove `ngOnInit` completely.
    this.achievementsFormArray = this.achievementsFormArray = this.fb.array([
      this.createAchievementFormGroup(),
    ]);
    this.achievementDetailsForm = this.fb.group({
      achievements: this.achievementsFormArray,
    });
  }

  // ...
}

HTML : HTML :

<div *ngFor="let achievement of achievementsFormArray.controls; let i = index" [formGroupName]="i">
...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 错误 TS7052:元素隐式具有“任何”类型,因为类型“AbstractControl”没有索引签名。 你的意思是叫'get'吗? - error TS7052: Element implicitly has an 'any' type because type 'AbstractControl' has no index signature. Did you mean to call 'get'? 元素隐含地具有“任何”类型,因为类型“AbstractControl”没有索引签名。 您的意思是调用“get”吗?ngtsc(7052) - Element implicitly has an 'any' type because type 'AbstractControl' has no index signature. Did you mean to call 'get'?ngtsc(7052) 错误 TS7053:元素隐式具有“任何”类型,因为“控件”类型的表达式不能用于索引类型“抽象控件”&lt;&gt; - error TS7053: Element implicitly has an 'any' type because expression of type '"controls"' can't be used to index type 'AbstractControl<> Angular - 元素隐式具有“任何”类型,因为类型“AbstractControl”没有索引签名 - Angular - Element implicitly has an 'any' type because type 'AbstractControl' has no index signature 元素隐式具有“任何”类型,因为 ANGULAR 中的类型表达式 - Element implicitly has an 'any' type because expression of type in ANGULAR TS (7015) 错误:元素隐式具有“任何”类型,因为索引表达式不是“数字”类型 - TS (7015) Error: Element implicitly has an 'any' type because index expression is not of type 'number' Typescript 使用 Angular 时出错“元素隐式具有‘任何’类型,因为类型‘‘课程’’的表达式不能用于索引‘对象’类型。” - Typescript error using Angular "Element implicitly has an 'any' type because expression of type '"courses"' can't be used to index type 'Object'." 元素隐式具有“任何”类型,因为类型“徽标”的表达式不能用于索引 Angular 中的类型“对象” - Element implicitly has an 'any' type because expression of type '"logo"' can't be used to index type 'Object' in Angular 编译器错误 TS7053:元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“Igame” - Compiler Error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Igame' 错误 TS7017:对象类型的索引签名在表单验证角度 2 中隐式具有“任何”类型 - error TS7017: Index signature of object type implicitly has an 'any' type in form validation angular 2
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM