typescript - mat-slide-toggle Angular Material สลับโปรแกรมโดยใช้โค้ด
ฉันกำลังพยายาม สลับ toggle() ผ่านโค้ด:
แม่แบบ
<mat-slide-toggle color="primary" (change)="updateFunc($event)"></mat-slide-toggle>
ts
updateFunc(e) {
// do some checks to see if can be activated
// if can't be activated, don't slide to on
e.checked = false; // <--- does not work
e.toggle(); // <-- does not work
}
มีไอเดียอะไรไหม?
--แก้ไข--
เพื่อให้ชัดเจน หลังจากเหตุการณ์การเปลี่ยนแปลง ปุ่มจะถูกสลับไปที่เปิด ฟังก์ชันของฉันจะทำงานเพื่อทดสอบบางอย่าง หากการทดสอบไม่ผ่าน ฉันต้องการสลับตัวเลื่อนกลับไปที่ตำแหน่งปิด ดังนั้นฉันจะสลับปุ่ม (เปิดหรือปิด) ในโค้ดของฉันได้อย่างไร นี่เป็นเพียงคำถามเกี่ยวกับการใช้เมธอด toggle() ในโค้ดของฉัน หรือการยกเลิกการเลือกสวิตช์ในโค้ดของฉัน
คำตอบ #1
https://stackblitz.com/edit/angular-material-edh46h
<mat-slide-toggle #toggleElement class="example-margin" [checked]="checked" (change)="updateFunc($event)">
Slide me!
</mat-slide-toggle>
@ViewChild("toggleElement") ref: ElementRef;
checked: boolean;
ngOnInit() {
this.checked = true;
}
updateFunc(e) {
const someCondition = true;
if (someCondition) {
this.ref.checked = false;
}
}
คำตอบ #2
คุณสามารถใช้ตัวแปรอ้างอิงเทมเพลตได้เท่านั้น
แม่แบบ
<mat-slide-toggle color="primary" #slide (change)="updateFunc(slide)">
</mat-slide-toggle>
ts
updateFunc(e) {
let var=false;
if(!var)
{
e.checked = true; //either true or false
}
