Как вставить шаблон-ссылку в другой компонент динамически угловой 5 - PullRequest
0 голосов
/ 27 апреля 2018

Я хочу создать шаблон (фрагмент HTML-кода) где-то еще, а затем динамически поместить этот код шаблона в некоторый целевой компонент.

Например: предположим, я создал шаблон, созданный в other-component

other.component.html

<ng-template #source>
      some code here....
</ng-template>

Теперь я хочу вставить этот шаблон в target-component из его контроллера.

target.component.html

<ng-content #target>
      to be inserted here....
</ng-content>

target.component.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.

1 Ответ

0 голосов
/ 02 мая 2018

Это может быть достигнуто с помощью *ngTemplateOutlet.

target.component.html

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

Нет необходимости создавать ContentChild.

target.component.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;
        <strike>if (v.sourceTemplate && this.targetContainer) {
            this.targetContainer.createEmbeddedView(v.sourceTemplate);
        }</strike>
    }

    <strike>@ContentChild('target') targetContainer;</strike>

    constructor() { }

    ngOnInit() { }

    ngAfterViewInit() {
        // output: After Modal view init: undefined
        <strike>console.log('After Modal view init: ', this.targetContainer);</strike>
    }

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...