简体   繁体   中英

How to insert a template-ref in other component dynamically angular 5

I want to create a template(a piece of html code) somewhere else and then put that template code to some target component dynamically.

For example: Suppose I have created a template which is created in other-component

other.component.html

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

Now I want to insert this template into target-component from its controller.

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);
    }

}

But above piece of code doesn't work, the reference to target targetContainer is undefined .

It can be achieved by *ngTemplateOutlet .

target.component.html

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

There is no need of instantiating a 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;
        
  
 
  
  
    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); 
  
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM