Создать держатель компонента - PullRequest
0 голосов
/ 18 декабря 2018

Как создать компонент, который действует как список, но длина и содержание списка зависят от дочернего компонента, указанного в держателе компонента.

пример:

<parent-component>
  <child-component> content </child-component>
  <child-component> content </child-component>
  <child-component> content </child-component>
  <child-component> content </child-component>
  <child-component> content </child-component>
</parent-component>

ifвы знакомы с угловым материалом, желаемый результат такой же, как у MatStepperComponent.

Примечание: содержимое в каждом дочернем компоненте имеет совершенно отличную модель от другого.так что, в основном, внедрение компонентов вместо модели данных

Ответы [ 2 ]

0 голосов
/ 20 декабря 2018

Идея, стоящая за этим вопросом, заключалась в создании компонента, который включает несколько дочерних компонентов, и, в зависимости от их количества, оболочка становится списком.

Вопрос: зачем мне это реализовывать?

Ответ: Представьте, что вы хотите создать что-то вроде степпера.

<stepper>
  <step> <component-a> </step>
  <step> <component-b> </step>
  <step> <component-c> </step>
</stepper>

решение, к которому я пришел, заключается в следующем:

StepComponent

step.htm

<ng-template>
  <ng-content></ng-content>
</ng-template>

step-component.ts

@ViewChild(TemplateRef)
public stepContainerRef: TemplateRef<any>;

constructor() {
}

ngOnInit() {
}

StepperComponent

stepper.html

<div *ngFor="let step of steps; let elementIndex = index">
  <ng-container [ngTemplateOutlet]="step.stepContainerRef"></ng-container>
</div>

stepper-component.ts

 @ContentChildren(StepComponent) steps: QueryList<StepComponent> = new QueryList<StepComponent>();

и le tour est joué .

для получения более подробной информации и понимания, пожалуйста, обратитесь кследующие ссылки:

0 голосов
/ 18 декабря 2018

Вы можете повторять полученные данные в ngFor.

Вот простая логика.В данном примере это тип данных, которые я использую:

[{
        "name": "John",
        "age": 30,
        "role": "Actor"
    },
    {
        "name": "Elys",
        "age": 22,
        "role": "The main one"
    },
  {
    "name": "Jhon",
    "age": 44,
    "role": "a random role"
  }
]

(поддельная) служба, которая извлекает данные:

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

    @Injectable()
    export class MainService{

    private data = [{
            "name": "John",
            "age": 30,
            "role": "Actor"
        },
        {
            "name": "Elys",
            "age": 22,
            "role": "The main one"
        },
      {
        "name": "Jhon",
        "age": 44,
        "role": "a random role"
      }
    ]
      constructor(){}
      public getData(){
        return this.data;
      }
    }

The main component: 

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

import { ChildComponent } from './child.component'
import { MainService } from './main.service'
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  data: any;
  constructor(private service: MainService){
    this.data = this.service.getData();
  }
}
<h2>The list above is created dinamically

  <hr>

  <ng-container *ngFor="let item of data">
    <child-cmp [data]="item"></child-cmp>
    <br>
  </ng-container>

дочерний компонент

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

@Component({
  selector: 'child-cmp',
  templateUrl: './child.component.html'
})
export class ChildComponent  {
  @Input() data: any;
}
<div style="display: flex; flex-direction: row">
  <span style="margin-right: 10px"> {{data.name}}</span>
  <span style="margin-right: 10px"> {{data.age}}</span>
  <span style="margin-right: 10px"> {{data.role}}</span>
</div>

Примечание Я использовал ng-container для итерации, потому что angular не отображает ее.

Рабочий стекблиц: https://stackblitz.com/edit/angular-2svnpt

...