我想要组件设置templateUrl
与一个变量,但它不起作用。
@Component({
selector: 'article',
templateUrl: '{{article.html}}',
styleUrls: ['styles/stylesheets/article.component.css']
})
export class ArticleComponent implements OnInit {
constructor(private route: ActivatedRoute, private articleService: ArticleService) { }
articleArray = this.articleService.getArticles();
article: Article;
ngOnInit(): void {
this.route.params.forEach((params: Params) => {
let headline = params['headline'];
this.article = this.articleService.getArticle(headline)
});
}
}
我到处都只能看到 Angular 1.X 的解决方案,这真的很令人沮丧。我查看了浏览器控制台,发现 {{article.html}} 甚至没有解析。读起来就是这样。当我自己设置路径时,它工作得很好,所以我知道问题不在于任何地方,而在于这里。
我认为你应该使用动态组件加载来做到这一点。
假设我们有一个 json 文件:
{
"title": "My first article",
"html": "app/articles/first.html"
}
我们可能会创造Html输出指令将根据需要动态创建组件模板网址:
@Directive({
selector: 'html-outlet'
})
export class HtmlOutlet {
@Input() html: string;
constructor(private vcRef: ViewContainerRef, private compiler: Compiler) {}
ngOnChanges() {
const html = this.html;
if (!html) return;
@Component({
selector: 'dynamic-comp',
templateUrl: html
})
class DynamicHtmlComponent { };
@NgModule({
imports: [CommonModule],
declarations: [DynamicHtmlComponent]
})
class DynamicHtmlModule {}
this.compiler.compileModuleAndAllComponentsAsync(DynamicHtmlModule)
.then(factory => {
const compFactory = factory.componentFactories
.find(x => x.componentType === DynamicHtmlComponent);
const cmpRef = this.vcRef.createComponent(compFactory, 0);
cmpRef.instance.prop = 'test';
cmpRef.instance.outputChange.subscribe(()=>...);;
});
}
}
然后像这样使用它:
<html-outlet [html]="article?.html">
Where html
是文章 html 的路径
在此查看更多详细信息Plunkr https://plnkr.co/edit/S5rhnK876tejAOyrTOy3?p=preview
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)