我有一张表,其中包含多个不止一个mat-slide-toggle元素。当我更改它们的任何值时,我想存储它们中已更改的值,因此我需要每个属性的id和true或false属性。我找到了FormControl来控制事件,但其中没有id属性。
.HTML
<tr *ngFor="let not of notifications;let i = index"
[ngStyle]="{ 'background-color': (not.isFinished ? '#dddddd' : 'white') }">
<th scope="row">{{i + 1}}</th>
<td>{{not.task}}</td>
<td>
<section class="example-section">
<mat-slide-toggle
class="example-margin"
[id]="i"
[color]="color"
[checked]="not.isFinished"
[disabled]="not.isFinished"
(toggleChange)="onToggleChange($event)"
[formControl]="activate"
>
</mat-slide-toggle>
</section>
</td>
</tr>
.TS
activate = new FormControl();
onToggleChange() {
console.log(this.activate.value);
}
更新
我已经解决了这个问题的朋友。感谢您的所有回答,我将在这里分享我的解决方案,以帮助遇到此问题的人们。我找到了(change)="onChange($event)"
并绑定了ID
。
HTML
<td>
<section class="example-section">
<mat-slide-toggle
[id]="i"
class="example-margin"
[color]="color"
[checked]="not.isFinished"
[disabled]="not.isFinished"
(change)="onChange($event)"
>
</mat-slide-toggle>
</section>
</td>
TScript
onChange(value: MatSlideToggleChange) {
console.log(value);
}
答案 0 :(得分:0)
除非您为其分配id属性,否则它将没有id属性。您可以使用索引添加id属性。从那里可以添加一个事件侦听器,即单击或更改并传入$ event变量以获取有关刚刚触发的事件的任何信息。
答案 1 :(得分:0)
将数据传递给组件函数非常简单-您可以从模板传递任何想要的数据。您可以根据需要通过setGlobal
或i
。
not
// template
(toggleChange)="onToggleChange(i, not)"
注意:// component
onToggleChange(i: number, not) {
}
不会发出toggleChange
。也许您想使用发射类型为$event
-API docs
(change)
MatSlideToggleChange
// template
(change)="onToggleChange($event, i, not)"
答案 2 :(得分:0)
您需要使用FormArray。
<tr *ngFor="let not of notifications;let i = index" >
<th scope="row">{{i + 1}}</th>
<td>{{not.task}}</td>
<td>
<section class="example-section">
<mat-slide-toggle
[formControl]="forms.controls[i]">
</mat-slide-toggle>
</section>
</td>
</tr>
<button (click)="console()">console values</button>
import {Component} from '@angular/core';
import { FormBuilder } from '@angular/forms';
/**
* @title Basic slide-toggles
*/
@Component({
selector: 'slide-toggle-overview-example',
templateUrl: 'slide-toggle-overview-example.html',
styleUrls: ['slide-toggle-overview-example.css'],
})
export class SlideToggleOverviewExample {
notifications = [
{
isFinished: false
},
{
isFinished: true
},
{
isFinished: false
},
{
isFinished: true
}
]
forms;
constructor(private formBuilder: FormBuilder) {
this.forms = this.formBuilder.array(
this.notifications.map(e => this.formBuilder.control(e.isFinished))
);
}
console() {
console.log(this.forms.value)
}
}
https://stackblitz.com/edit/angular-wte1qt?file=app/slide-toggle-overview-example.ts
答案 3 :(得分:-1)
class Something:
def __init__(self):
self.attr = 0
def validate(self):
# doesn't want to perform validation
pass
class SubclassOfSomething(Something):
def __init__(self):
Something.__init__(self)
def validate(self):
if self.attr < 0:
raise ValueError()