Angular组件库ng-zorro-antd实现radio单选框选择(angular组件库开发)干货满满

随心笔谈11个月前发布 admin
92 0

@Injectable()
export class NzRadioService {
selected$=new ReplaySubject<NzSafeAny>(1);
touched$=new Subject<void>();
disabled$=new ReplaySubject<boolean>(1);
name$=new ReplaySubject<string>(1);
touch(): void {
this.touched$.next();
}
select(value: NzSafeAny): void {
this.selected$.next(value);
}
setDisabled(value: boolean): void {
this.disabled$.next(value);
}
setName(value: string): void {
this.name$.next(value);
}
}
// radio.component.ts====> ngOnInit
this.nzRadioService.selected$.pipe(takeUntil(this.destroy$)).subscribe(value=> {
const isChecked=this.isChecked;
this.isChecked=this.nzValue===value;
// We don’t have to run `onChange()` on each `nz-radio` button whenever the `selected$` emits.
// If we have 8 `nz-radio` buttons within the `nz-radio-group` and they’re all connected with
// `ngModel` or `formControl` then `onChange()` will be called 8 times for each `nz-radio` button.
// We prevent this by checking if `isChecked` has been changed or not.
if (
this.isNgModel &&
isChecked !==this.isChecked &&
// We’re only intereted if `isChecked` has been changed to `false` value to emit `false` to the ascendant form,
// since we already emit `true` within the `setupClickListener`.
this.isChecked===false
) {
this.onChange(false);
}
this.cdr.markForCheck();
});

© 版权声明

相关文章