[英]ViewChild of script tag returns undefined
I need to access a script tag with ViewChild but it returns undefined when I try to access to nativeElement
.我需要使用 ViewChild 访问脚本标记,但是当我尝试访问时它返回 undefined
nativeElement
。 It is working with a normal <p>
tag but not with <script>
.它正在使用普通的
<p>
标签,但不适用于<script>
。
Here is the stackblitz with an example (with p
and script
). 这是带有示例的 stackblitz (带有
p
和script
)。
I basically do:我基本上是这样做的:
@ViewChild('pRef', {static: false}) pRef: ElementRef;
and the in ngAfterViewInit():以及在 ngAfterViewInit() 中:
this.pRef.nativeElement.innerHTML = "DOM updated succesfully!!!";
User Renderer2 and Document to inject your script dynamically.用户 Renderer2 和 Document 动态注入您的脚本。
in app.component.ts在 app.component.ts
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit {
name = 'Angular';
@ViewChild('pRef', {static: false}) script: ElementRef;
@ViewChild('prefworking', {static: false}) prefworking: ElementRef;
constructor(
private _renderer2: Renderer2,
@Inject(DOCUMENT) private _document: Document
) { }
ngAfterViewInit() {
this.prefworking.nativeElement.innerHTML = "Working pref";
this.convertToScript();
}
convertToScript() {
let script = this._renderer2.createElement('script');
script.type = `text/javascript`;
this._renderer2.appendChild(this._document.body, script);
}
}
I have created the stackblitz.我创建了stackblitz。 checkout this link https://stackblitz.com/edit/angular-8-viewchild-example-gaffzs
查看此链接https://stackblitz.com/edit/angular-8-viewchild-example-gaffzs
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.