简体   繁体   English

Ajax调用和html渲染后的角度访问数据

[英]Angular accessing data after ajax call and render of html

Hi I am trying to figure this out but have yet to do so. 嗨,我正在尝试解决这个问题,但尚未做到。 All help is much appreciated. 非常感谢所有帮助。

I have an element inside my component: 我的组件中有一个元素:

 <div [innerHtml]="reportData" class="widget" #reportDisplayHost></div>

Then I have an ajax call that returns a string I bind the return string as such: 然后我有一个ajax调用返回一个字符串,我将返回字符串绑定为:

this.reportData = this.sanitizer.bypassSecurityTrustHtml(response);

Once the html data is rendered I want to access some nested elements like so: 呈现html数据后,我想访问一些嵌套元素,如下所示:

@ViewChild('reportDisplayHost') reportDisplayHost: ElementRef<any>;
console.log(this.reportDisplayHost.nativeElement.querySelector('chart'));

I when I tried to do this I get a null but I see the element on the page. 当我尝试执行此操作时,我得到一个null,但我在页面上看到了该元素。

<chart exportenabled="1" showalternatehgridcolor="0" basefontsize="11" basefont="Roboto" showborder="0" bgcolor="#ffffff" showshadow="0" use3dlighting="0" legendshadow="0" legendbordercolor="ffffff" showlegend="1" useplotgradientcolor="0" showplotborder="0" showcanvasborder="0" palettecolors="26478d" useroundedges="0" labeldisplay="Rotate" slantlabels="1" yaxismaxvalue="100" yaxisminvalue="0" showvalues="1" yaxisname="Score" xaxisname="Month" caption="Quarterly Score Trends">

<set name="APR-JUN" value="4">&nbsp;</set>
<set name="JUL-SEP" value="7">&nbsp;</set>
<set name="OCT-DEC" value="3">&nbsp;</set>                                                                                                                           
<set name="JAN-MAR" value="3">&nbsp;</set>   
</chart>

How can I do this? 我怎样才能做到这一点?

Thanks in advance! 提前致谢!

After you assign this.reportData , you want to give Angular a chance to update the DOM before you start querying for child nodes. 分配this.reportData ,您想让Angular有机会在开始查询子节点之前更新DOM。

You can call ChangeDetectorRef.detectChanges() to trigger a change detection run before you query for the updated DOM: 您可以在查询更新的DOM之前调用ChangeDetectorRef.detectChanges()触发更改检测运行:

constructor(private cd: ChangeDetectorRef, private sanitizer: DomSanitizer) {}

// ...

this.reportData = this.sanitizer.bypassSecurityTrustHtml(html);

// Update the DOM
this.cd.detectChanges();

// Now we can access the updated DOM
console.log(this.reportDisplayHost.nativeElement.querySelector('chart'));

And here's a StackBlitz example . 这是一个StackBlitz示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM