1

我想在其他地方创建一个模板(一段 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);
    }

}

但是上面这段代码不起作用,对目标的引用targetContainerundefined.

4

1 回答 1

0

可以通过*ngTemplateOutlet.

target.component.html

<ng-template #defaultTemplate></ng-template>
<ng-content *ngTemplateOutlet="hmConfig.sourceTemplate || defaultTemplate">
    to be inserted here....
</ng-content>

不需要实例化 a ContentChild

目标组件.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);
    }

}
于 2018-05-02T12:22:03.297 回答