是的,您可以在从外部源加载的模板中进行数据绑定。下面是一个使用 Angular 8 的示例:
首先,在组件中定义一个变量来保存模板的内容:
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-template',
templateUrl: './template.component.html',
styleUrls: ['./template.component.css']
})
export class TemplateComponent implements OnInit {
templateContent: string;
constructor(private http: HttpClient) { }
ngOnInit() {
// 从外部源加载模板
this.http.get('http://example.com/template.html', { responseType: 'text' })
.subscribe((response) => {
this.templateContent = response;
});
}
}
然后,在模板中使用 innerHTML
属性来加载外部模板:
这样,模板的内容就会被加载并显示在 请注意,在加载外部模板时,可能会遇到跨域访问的问题。解决方法可以参考 Angular 的跨域访问文档。 另外,使用 innerHTML
属性时要小心,因为它可能会导致安全漏洞,例如注入恶意脚本。请确保加载的模板是可信任的。相关内容