我想在其他地方创建一个模板(一段 html 代码),然后将该模板代码动态地放到某个目标组件中。
例如:假设我创建了一个模板,该模板是在other-component
其他.component.html
<ng-template #source>
some code here....
</ng-template>
target-component现在我想从它的控制器中插入这个模板。
target.component.html
<ng-content #target>
to be inserted here....
</ng-content>
目标组件.js
@Component({
selector: 'app-target',
templateUrl: './target.component.html'
})
export class TargetComponent implements OnInit, AfterViewInit {
private _config: Config;
@Input()
get hmConfig(): Config {
return this._config;
}
set hmConfig(v: Config) {
this._config = v;
if (v.sourceTemplate && this.targetContainer) {
this.targetContainer.createEmbeddedView(v.sourceTemplate);
}
}
@ContentChild('target') targetContainer;
constructor() { }
ngOnInit() { }
ngAfterViewInit() {
// output: After Modal view init: undefined
console.log('After Modal view init: ', this.targetContainer);
}
}
但是上面这段代码不起作用,对目标的引用targetContainer是undefined.