TLDR; 您需要在元素被注入 DOM 后调用 componentHandler.upgradeElement。下面的示例描述了我过去使用的一种方法。
编辑如果您想要一个声明性解决方案this approach here 似乎是一个不错的解决方案,但我自己没有使用它。
我创建了一个包装 Material Lite 组件处理程序的服务
import { Injectable } from '@angular/core';
export interface ComponentHandler {
upgradeDom();
}
declare var componentHandler: ComponentHandler;
@Injectable()
export class MaterialService {
handler: ComponentHandler;
constructor() {
this.handler = componentHandler;
}
// render on next tick
render() {
setTimeout(() => { this.handler.upgradeDom(); }, 0);
}
}
然后在组件将元素注入 DOM 后调用服务的渲染函数。在您的情况下,这是在 *ngFor
之后
这是一个非常人为的例子,但演示了“在哪里”调用渲染
import { Component, OnInit } from '@angular/core';
import { DataService } from 'services/data.service';
import { MaterialService } from 'services/material.service';
@Component({
selector: 'app-thing',
templateUrl: `
<ul>
<li *ngFor="let item of data">
{{data}}
</li>
</ul>
`
})
export class ThingComponent implements OnInit {
data: string[]
constructor(
private service: DataService,
private material: MaterialService
) { }
ngOnInit() {
this.service.getData()
.subscribe(data => {
this.data = data;
this.material.render();
});
}
}