我有一个角度应用程序,可以从Firebase Firestore提取数据。在每个组件中,我根据组件的高度和宽度动态设置背景笔画。问题在于,在从服务器加载数据的组件中,高度无法计算。我正在使用指令计算宽度和高度并设置笔划
四处阅读,我发现很多人提到changeDetectionRef,但是我不知道如何实现它。下面是我的代码(指令)
import { Directive, ElementRef, AfterViewInit, Renderer2, ChangeDetectorRef } from '@angular/core';
import { strokes } from '@constants/strokes';
@Directive({
selector: '[appStrokes]'
})
export class StrokesDirective implements AfterViewInit {
constructor(
private elementRef: ElementRef,
private renderer: Renderer2,
private changeDetector: ChangeDetectorRef
) {}
ngAfterViewInit() {
const element = this.elementRef.nativeElement as HTMLElement;
const width = element.offsetWidth;
const height = element.offsetHeight;
this.renderer.setStyle(
this.elementRef.nativeElement,
'background',
this.randomize(width, height)
);
}
private randomize(width: number, height: number): string {
let random = this.randomProperties(width, height);
for (let i = 0; i < 16; i++) {
random += ', ' + this.randomProperties(width, height);
}
return random;
}
private randomProperties(offsetWidth: number, offsetHeight: number): string {
// url property
const i = Math.floor(Math.random() * strokes.length);
const url = strokes[i];
// position property
const x = Math.floor(Math.random() * offsetWidth) + 'px ';
const y = Math.floor(Math.random() * offsetHeight) + 'px/';
const position = x + y;
// size property
const h = 'auto ';
const w = Math.floor(Math.random() * (150 - 50) + 50) + 'px ';
const size = w + h;
// repeat property
const repeat = 'no-repeat';
// return properties
return url + position + size + repeat;
}
}
答案 0 :(得分:0)
您只需将ngAfterViewInit()
中的代码放入其自己的方法中,然后在Firebase调用的回调中调用该方法。例如,如果您使用HttpClient
调用API:
result$ = this.httpClient.get('/foo');
result$.subscribe(res => {
this.updateBackgroundColour();
});