我正在尝试基于对象属性的值来启用/禁用mat-inputs
。
在我的组件中,我正在订阅服务中的observable
,它将返回默认情况下将禁用标志设置为true
的所有应用程序,以表示我的字段应该被禁用。我成功地获得了我的申请,没有任何问题。
在我看来,我有一个表来显示应用程序,每行显示一对mat-inputs
,应根据application.disabled
标志启用或禁用由mat-checkbox (click)
事件驱动。
我的问题是,在填充表格时,没有禁用任何mat-input,只有在一次选中并取消选中该复选框后,该输入才被禁用,然后该行将正常运行。
如何使我的默认禁用状态在所有字段中传播,又如何保持基于对象的禁用属性值启用/禁用的功能?
application.viewmodel.ts
import { ApplicationDto } from '../models';
export class ApplicationViewModel {
disabled: boolean;
application: ApplicationDto;
constructor(
disabled?: boolean,
application?: ApplicationDto
) {
this.disabled = disabled || false;
this.application = application || null;
}
}
application.service.ts
export class ApplicationService {
private currentApplicationsSubject = new BehaviorSubject<ApplicationViewModel[]>([]);
get currentApplications$(): Observable<ApplicationViewModel[]> {
return this.currentApplicationsSubject.asObservable();
}
constructor(private http: HttpClient) { }
// Fetch all applications
fetchApplications(): void {
this.http.get<ResponseDto<CollectionDto<ApplicationDto>>>
(location.origin + '/api/application').pipe(
map((response: ResponseDto<CollectionDto<ApplicationDto>>)
=> response.response.collection)
).subscribe(
(dtos: ApplicationDto[]) => {
let viewModels: ApplicationViewModel[] = [];
dtos.forEach(dto => viewModels.push(new ApplicationViewModel(true, dto)));
this.currentApplicationsSubject.next(viewModels);
}
);
}
}
application.component.ts
// Datasource
dataSource = new MatTableDataSource<ApplicationViewModel>();
// Get and set currentApplications BehaviorSubject from web request
this.applicationService.fetchApplications();
// Observable subscription
this.service.currentApplications$.subscribe(
(applications: ApplicationViewModel[]) => this.dataSource.data = applications
);
// Disabled state changer
changeRowState(application: ApplicationViewModel) {
application.disabled = !application.disabled;
}
application.component.html
<table mat-table fxFlex="grow" [dataSource]="dataSource">
<ng-container matColumnDef="select">
<th mat-header-cell *matHeaderCellDef>Select</th>
<td mat-cell *matCellDef="let application">
<mat-checkbox
(click)="$event.stopPropagation(); changeRowState(application);"
(change)="$event ? selection.toggle(application) : null"
[checked]="selection.isSelected(application)">
</mat-checkbox>
</td>
</ng-container>
<ng-container matColumnDef="field">
<th mat-header-cell *matHeaderCellDef>Field</th>
<td mat-cell *matCellDef="let application">
<input
matInput
placeholder="Field"
[attr.disabled]="application?.disabled ? '' : null"
required />
</td>
</ng-container>
...
答案 0 :(得分:1)
直接使用
[disabled]="application?.disabled ? '' : null"