Angular pass multiple templates to Component

后端 未结 2 1767
孤城傲影
孤城傲影 2020-12-25 09:20

I\'m trying to create a component that accepts multiple templates as inputs. This is the example I have:

@Component({
    selector: \'data-list\',
    styles         


        
相关标签:
2条回答
  • 2020-12-25 09:38

    I solved this same issue by using the string selector available to the ContentChild decorator.

    You will need to specify template variables when using your data-list component:

    <data-list [itemsData]="data">
        <ng-template #firstItemTemplate let-item>
            <h1 style="color:red;">{{ item.header }}</h1>
            <div>{{ item.content }}</div>
        </ng-template>
        <ng-template #standardTemplate let-item>
            <h1>{{ item.header }}</h1>
            <div>{{ item.content }}</div>
        </ng-template>
    </data-list>
    

    Then, inside your data-list component class, assign the template variables to local variables on the component:

    @Input() itemsData: any[];
    @ContentChild('firstItemTemplate') firstItemTemplate: TemplateRef<ElementRef>;
    @ContentChild('standardTemplate') standardTemplate: TemplateRef<ElementRef>;
    

    After this, you'll be able to render the passed-in templates from your data-list component.

    @Component({
        selector: 'data-list',
        styles: [
            require('./data-list.component.scss')
        ],
        template: `
            <span *ngFor="let item of itemsData; let i = index" >
                <ng-template *ngIf="i == 0; else nextTmpl"
                    ngFor let-item [ngForOf]="[item]" [ngForTemplate]="firstItemTemplate"
                ></ng-template>
                <ng-template #nextTmpl 
                    ngFor let-item [ngForOf]="[item]" [ngForTemplate]="standardTemplate"
                ></ng-template>
            </span>
        `
    })
    
    0 讨论(0)
  • 2020-12-25 09:56

    Try this instead.

    @Component({
        selector: 'data-list',
        styles: [
            require('./data-list.component.scss')
        ],
        template: `
            <ng-template ngFor [ngForOf]="itemsData" [ngForTemplate]="itemTemplate"></ng-template>
        `
    })
    
    export class DataListComponent {
        @Input() itemsData: any[];
        @ContentChild(TemplateRef) itemTemplate: TemplateRef<ElementRef>;
    }
    
    0 讨论(0)
提交回复
热议问题