我使用的D3与Angular2,后面的例子here。我的部分是这样的:如何处理需要AfterViewInit的OnChanges
@Component({
selector: 'example-component',
template: '<div #someElement></div>'
})
class exampleComponent implements OnChanges, AfterViewInit {
@ViewChild('someElement') someElement: any;
@Input() someInput: any; //got from API in service provided by parent component
htmlElement: any;
selection: any;
ngAfterViewInit() {
this.htmlElement = this.someElement.nativeElement;
this.selection = D3.select(this.htmlElement);
}
ngOnChanges() {
if (!this.someInput) return;
this.selection.append('svg');
// continue to build chart
}
}
的问题,这是输入可以随时ngAfterViewInit
被调用之前。 if
语句可防止在输入准备就绪之前生成图表,但如果在ngAfterViewInit
之前已准备就绪,则在调用ngOnChanges
时将不确定this.selection
。然而一个无法加入其他条件这样this.selection
:
if (!this.someInput || !this.selection) return;
因为那么图表将不会在所有的情况下建造当输入就绪之前ngAfterViewInit
因为ngOnChanges
不一定会再次ngAfterViewInit
后调用。
对于这种情况是否有最佳做法?我意识到几乎总是输入在ngAfterViewInit
之前不会准备好,但它是可能的。有一些类似的担忧表明here,但它不完全相同。
提前致谢!
编辑:更多的试验后,看来我可以在ngOnChanges
做
this.htmlElement = this.someElement.nativeElement;
this.selection = D3.select(this.htmlElement);
,甚至ngAfterViewInit
之前,这是令人惊讶的。
能否详细介绍一下在这种情况下如何使用它?不知道这将如何帮助我确保视图已经初始化并且输入已经准备好,然后再继续构建图表 –
我考虑了一下,并且对ngOnChanges中的第一次修改和构建第一个图表在'ngAfterViewInit'中。然后在以后的更改中,图表将被重建。也许添加这个到你的答案。谢谢! –