I have this select inside a form in the HTML from which I retrieve the ID of the selected value.
<mat-form-field>
<mat-label>Select an user</mat-label>
<mat-select disableRipple #selectVal id="valueSelect" formControlName="user"
(selectionChange)="idUser($event.value)">
<mat-option #userPost id="userPostId" *ngFor="let user of users"
[value]="user.id">{{user.name}}</mat-option>
</mat-select>
</mat-form-field>
And with this method I recover the id of the select in my component.ts
idUser(value: any) {
console.log(value);
}
Only that the id of the select I actually need within this other method which will then be used to add a new post. To be precise, I have to update the value of this.postService.userid of the following method:
addPost(title: string, body: string): void {
title = title.trim();
body = body.trim();
this.postService.APIkey = this.urlToken as string
this.postService.userid = // HERE I need the ID value of the select
this.postService.addPosts(title, body).subscribe((data) => {
window.location.reload()
},
(error)=>{
if (error.status) {
alert('Error: ' JSON.stringify(error.error));
}
});
}
Is there any way to do this? I can't find any viable alternative. Can anyone help me?
CodePudding user response:
One way to do this would be to store the value of the selected option in a property of your component and then use that property when calling the addPost method.
In your component's class, add a property to store the value of the selected option:
selectedUserId: string;
In the idUser
method, update the selectedUserId
property with the value of the selected option:
idUser(value: any) {
console.log(value);
this.selectedUserId = value;
}
In the addPost
method use the selectedUserId
property to set the userid property of the postService
:
addPost(title: string, body: string): void {
title = title.trim();
body = body.trim();
this.postService.APIkey = this.urlToken as string;
this.postService.userid = this.selectedUserId;
this.postService.addPosts(title, body).subscribe((data) => {
window.location.reload()
},
(error)=>{
if (error.status) {
alert('Error: ' JSON.stringify(error.error));
}
});
}