Content

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

文章摘要

这篇文章介绍了如何使用NzRadioService组件和Subject/ReplaySubject事件处理来实现对 radio 钮的响应。文章详细说明了如何通过`touch()`、`select()`、`setDisabled()`和`setName()`方法触发相关事件。特别地,在`ngOnInit`中,文章展示了如何通过管道和`takeUntil`绑定服务,并通过订阅事件来更新`isChecked`状态。文章还强调了性能优化,避免了多次调用`onChange()`,从而提高应用程序的响应速度。

@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(); });