紀錄一下按鈕自訂元件處理
事後 signal 練習
export class ButtonDebounceComponent implements AfterViewInit {
@ViewChild('btn') btn!: ElementRef
buttonText = signal<string>('我是按鈕')
ngAfterViewInit() {
const click$ = fromEvent(this.btn.nativeElement, 'click')
click$.subscribe(()=>{
console.log('瓜')
})
}
}
ngAfterViewInit() {
if (this.btn) {
this.buttonClick = toSignal(fromEvent(this.btn.nativeElement, 'click')
.pipe(tap((event) => {
console.log('瓜',event)
})));
} else {
console.error('Button element is not yet available');
}
}
runInInjectionContext
injection context & runInInjectionContext 認真該看
<p>
初始值是否是阿拉花瓜 :{{buttonClick() ==='阿拉花瓜'}}
</p>
this.buttonClick = toSignal(
fromEvent(this.btn.nativeElement, 'click')
.pipe(tap(() => {
console.log('睡不飽拉')
})),
{initialValue:'阿拉花瓜'} //設定初始值
);
export class ButtonDebounceComponent {
@ViewChild('btn') btn!: ElementRef
buttonText = signal<string>('我是按鈕')
debounceInput = input<number>(0)
buttonClick: Signal<any> | null = null
private readonly injector = inject(Injector);
count = 0; //計數器
ngAfterViewInit() {
runInInjectionContext(this.injector, () => {
if (this.btn) {
this.buttonClick = toSignal(
fromEvent(this.btn.nativeElement, 'click')
.pipe(
tap(() => {
console.log('睡不飽拉')
}),
debounceTime(this.debounceInput()),
tap(()=> this.count++)
),
{ initialValue: '阿拉花瓜' } //設定初始值
);
} else {
console.error('Button element is not yet available');
}
});
}
}