我有一个函数,它从文件中获取 html 内容作为字符串。之后我把它作为一个 html 对象。我可以在控制台中清楚地看到它有效。如何将其从服务传递到 div 元素?
nav.service.ts:
html: string;
public getZipFileContent(urlPath:string, pathInZip:string, ) {
getFileContentFromRemoteZip(urlPath, pathInZip, (content) => {
console.log(content);
let html = content;
let htmlObject = document.createElement('div');
htmlObject.innerHTML = html;
console.log(htmlObject);
this.html = html; // it's a string
this.html = htmlObject // error : can't asign string as HTMLdivElement
});
}
}
通过在我的组件中添加 {{navSrv.html}} 现在我得到了什么:
我想要得到什么:
你好
Console.log 来自:console.log(htmlObject);
如何获取 htmlObject 并将其用作变量?
最佳答案
如果你想在div中使用它,你可以像follow一样这样做
<div [innerHtml]="navSrv.html"></div>
除此之外,您还可以像下面这样做:
<div #divID ></div>
然后像这样绑定(bind)
@ViewChild('divID') divID: ElementRef;
loadHtml(){
this.divID.nativeElement.innerHTML = this.html;
}
当 html 字符串非常大时,第二部分很有用。
编辑
根据您的要求,如果您有<script>
标签然后你可以这样做,如果如下
const element = document.createRange().createContextualFragment(this.html);
this.divID.appendChild(fragment);
关于javascript - Angular typescript如何将字符串转换为html对象并将其传递给变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49916179/