Dynamic template based on value rather than variable with ngTemplateOutlet

前端 未结 3 1870
花落未央
花落未央 2021-01-13 04:51

I\'m trying to mock up a dynamic set of questions. Think of a quiz, where one question is multiple choice, the second is single answer, the third is yes no..etc.

Us

3条回答
  •  爱一瞬间的悲伤
    2021-01-13 05:40

    As i said in comment you have to pass TemplateRef for ngTemplateOutlet property. It could be done like this:

    @Directive({
      selector: 'ng-template[type]'
    })
    export class QuestionTemplate {
      @Input() type: string;
      constructor(public template: TemplateRef) {}
    }
    

    app.html

    
      ...
      ...
      ...
    

    my.component.ts

    @Component({
      selector: 'my-component',
      template: `
        
    ` }) export class MyComponent { @Input() items: any[]; @ContentChildren(QuestionTemplate) templates: QueryList; dict = {}; ngAfterContentInit() { this.templates.forEach(x => this.dict[x.type] = x.template); } }

    Plunker Example

提交回复
热议问题