Reputation: 373
I have an issue with types in my Angular component. I have a form that gets a value from input and sends data to server. I want the data to have type specs: string[]
but the compiler throws me an error:
Type 'number' is not assignable to type 'any[]'
Howewer if I change it to specs = []
it works well. I searched Angular and TypeScript docs for explaining but didn't find any answer for my issue.
Here is my HTML component:
<div class="container list-group" [formGroup]="specForm" (ngSubmit)="setSpec()">
<div class="list-group-item information">
Speciality: <a href="#" class="header-picture"><img src="assets/static/img/edit.png" alt=""></a>
</div>
<div class="list-group-item info-field-list">
<div class="info-field-name">
<p>Sector:</p>
</div>
<div class="info-field-value" *ngFor="let user of users;let i=index">
<div class="info-field-value">
<a class="url"> {{user.speciality}} </a> (3lvl)
</div>
</div>
<div class="info-field-value">
<input type="text" class="spec-input" formControlName="speciality" placeholder="Write text"><span
class="icon icon-plus" (click)="setSpec()"></span>
</div>
</div>
</div>
And TS file:
import { Component, OnInit, Input } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { AuthenticationService } from '@services/auth.service';
@Component({
selector: 'app-speciality',
templateUrl: './speciality.component.html',
styleUrls: ['./speciality.component.css']
})
export class SpecialityComponent implements OnInit {
@Input() user;
specs: string[];
specForm: FormGroup;
submitted = false;
loading = false;
constructor(private formBuilder: FormBuilder, private authService: AuthenticationService) { }
ngOnInit() {
this.specForm = this.formBuilder.group({
speciality: ['']
});
this.authService.getUser().subscribe(
(data) => {
//this.specs = data.speciality;
});
}
get s() { return this.specForm.controls; }
setSpec() {
// activating submission flag for patch function
console.log(this.specs)
let newSpec = this.specs.push(this.s.speciality.value)
this.submitted = true;
console.log(this.specs)
if (!this.specForm.valid) {
return
}
this.authService
// sending values to auth service function
.specAdd(newSpec)
.subscribe(
(data) => {
this.submitted = false;
},
error => {
this.loading = false;
});
}
}
Any help would be appreciated.
Upvotes: 2
Views: 5661
Reputation: 11982
The problem is that you are assigning Array.push result to array, Array.push returns a number that shows the array length, just in first push to array then assign the array to new one:
let newSpec = this.specs.push(this.s.speciality.value)
should be:
this.specs.push(this.s.speciality.value)
let newSpec = this.specs
Upvotes: 4