从派生组件到基础组件的角度嵌入模板

问题描述 投票:0回答:1

我试图了解如何使用Angular组合。我的情况是我有一个问题列表,每个问题都有一个类型。基于该类型部分的模板更改。理想情况下,我认为我需要一个基本组件,它有自己的模板,它有一个ng-content占位符,派生组件会将其特定内容注入父组件。我是否需要将子模板创建为指令?这是我到目前为止所拥有的。

外模板

<questionnaire>
    <div *ngFor="let question of questions" [ngSwitch]="question.type">
        <question-type-a *ngSwitchCase="'A'" [question]="question"</question-type-a>
        <question-type-a *ngSwitchCase="'B'" [question]="question"</question-type-b>
        <question-type-a *ngSwitchCase="'C'" [question]="question"</question-type-c>
    </div>
</questionnaire>

问题部分

@Component({
  selector: 'question',
  templateUrl: './question.component.html'
})
export class QuestionComponent implements OnInit {
  @Input() question: IQuestion;

  constructor() { }

question.component.html模板

<div>
    <ng-container #details></ng-container>
    <button>do something</button>
</div>

问题类型 - 模板

<ng-template #mydetails>
   <button>Answer Question</button>
</ng-template>

问题类型 - 一个组件

@Component({
  selector: 'question-type-a',
  templateUrl: './question-type-a.html'
})
export class QuestionTypeAComponent extends QuestionComponent implements OnInit, AfterViewInit {
  @ViewChild("details", { read: ViewContainerRef }) details: 
ViewContainerRef;
   @ViewChild("mydetails") mydetails: TemplateRef<any>;
  @Input() question: IQuestion;

  constructor() {
    super();
  }

  ngOnInit() {
  }

  ngAfterViewInit(): void {
    let view = this.yesnotdetails.createEmbeddedView(null);
    this.details.insert(view);
  }
}

最后,我试图了解如何将派生组件中的#mydetails引入基本组件的#details容器中。显然,这不是正确的方法。我一直在搜索嵌入式模板和派生组件,但我无法完全理解如何完成我想要做的事情或找到一个符合我认为我需要的例子。构建这个的正确方法是什么,所以我可以有一个主模板和一个派生模板?

angular angular2-template angular-directive
1个回答
0
投票

你可以在角度使用content projection

例:

QuestionContainerComponent

import { Component } from '@angular/core';

@Component({
  selector: 'question-container',
  template: `
    <div class="question-container">
      <ng-content></ng-content>
    <div>`,  
})
export class QuestionContainerComponent  {}

QuestionComponent

import { Component, Input } from '@angular/core';

@Component({
  selector: 'question',
  template: `
    <div class="question">
      {{model}}
    <div>`,  
})
export class QuestionComponent  {
  @Input() model : any;
}

AppComponent

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
    <question-container>
      <div *ngFor="let question of questions" [ngSwitch]="question.type">
        <question *ngSwitchCase="1" [model]="question.value"></question>
        <question *ngSwitchCase="2" [model]="question.value"></question>
      </div>  
    </question-container>
  `,
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
    questions: any[] = [
      { type: 1, value: 'My question 01'},
      { type: 2, value: 'My question 02'},
      { type: 3, value: 'My question 02'},
      { type: 4, value: 'My question 02'},
    ];
}
© www.soinside.com 2019 - 2024. All rights reserved.