angular - How can I show my own text status before i switch my toggle button while using mat-slide-toggle
问题描述
When ever I start my page the toggle button shows but no text appears until I toggle the button.
When you click on it, it shows "on" but when you click it again, the toggle button doesn't switch and keeps saying "on", but when you click it one more time it does change to "off".
I want my page to show the correct toggle text when you load it, and when you press the button I want it to change correctly.
this is the html
<p>Toggle</p>
<mat-slide-toggle
[checked]="checked"
(click) = "hi()"
>{{toggle}}</mat-slide-toggle>
This is the component.ts file
checked = true;
toggle;
hi(){
if(this.checked == true){
this.toggle = "on"
this.checked = false;
}
else{
this.toggle = "off"
this.checked = true;
}
}
解决方案
According to the slide toggle API, you would use change
event instead of click
event. change
exposes an event of type MatSlideToggleChange
that has a checked
property that you can use to conditionally update your checked
and toggle
property values:
Component example:
import { Component } from '@angular/core';
import { MatSlideToggleChange } from '@angular/material/slide-toggle';
@Component({
selector: 'slide-toggle-overview-example',
templateUrl: 'slide-toggle-overview-example.html',
styleUrls: ['slide-toggle-overview-example.css'],
})
export class SlideToggleOverviewExample {
checked: boolean = false;
toggle: string = "off";
handleChange(event: MatSlideToggleChange) {
if (event.checked) {
this.toggle = "on"
this.checked = true;
} else {
this.toggle = "off"
this.checked = false;
}
}
}
HTML Sample:
<mat-slide-toggle [checked]="checked" (change)="handleChange($event)">Slide me!</mat-slide-toggle>
{{checked}}
{{toggle}}
Here is a simple example in action. You can adjust toggle
values as necessary as it's not clear what you are expecting to display.
Hopefully that helps!