...
<select class="form-control" (change)="onChange($event.target.value, 'status')" #byStatus>
<option value ="" disabled selected="selected">IBy Status</option>
<option>Pending</option>
<option>Paid</option>
</select>
</div>
<div class="col-xs-2">
<select class="form-control" (change)="onChange($event.target.value, 'user')" #byUser>
<option value ="" disabled selected="selected">By User</option>
<option *ngFor="let user of allUsers" value="{{user.id}}">{{user.first_name}} - {{user.email}}</option>
</select>
...
In the .ts
file I know which select input is selected. I tried to change the value buy using nativeElement
but
this.byStatus.nativeElement.ElementRef
is null .
How to set the value of select input to default if the other is selected. So if select input 1st is selected 2nd should be set to default and if 2nd is selected then 1 should be set to default
onChange(selectedVal: string, by: string) {
if (by === 'status') {
...
} else if (by === 'user') {
console.log(this.byStatus.nativeElement.ElementRef);
this.byStatus.nativeElement.ElementRef.value = "";
}
}
Rather than using nativeElement
to change your element, try using Template driven forms ( ngModel
) provided by Angular (See documentation: https://angular.io/guide/forms ). You can also use Reactive forms (See documentation: https://angular.io/guide/reactive-forms ). Both these methods will give you better control over your code.
To use ngModel
in your code. You will need to import the FormsModule
in your app.module.ts
app.modules.ts
import { FormsModule } from '@angular/forms';
@NgModule({
imports: [
FormsModule,
],
declarations: [
...
],
providers: [...],
bootstrap: [...]
})
export class AppModule {}
In your HTML, set the ngModel
attribute to your select tags to bind the values to the component. With this, when you select an item from the status
dropdown, it will update selectedStatus
to the value of the selected option.
<select class="form-control" (change)="onChange('status')" [(ngModel)]="selectedStatus">
<option value="" disabled selected="selected">IBy Status</option>
<option>Pending</option>
<option>Paid</option>
</select>
<select class="form-control" (change)="onChange('user')" [(ngModel)]="selectedUser">
<option value="" disabled selected="selected">By User</option>
<option *ngFor="let user of allUsers" value="{{user.id}}">{{user.first_name}} - {{user.email}}</option>
</select>
Then in your component, declare the required and set them to the default value.
selectedUser: any = "";
selectedStatus: any = "";
onChange(changedDropdown: string) {
if (changedDropdown === 'user') {
this.selectedStatus = "";
} else {
this.selectedUser = "";
}
}
Here is a working example of the same on Stackblitz
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.