如何根据数据动态加载应用程序组件?

时间:2019-04-07 10:43:35

标签: angular typescript

在angular项目中,我想基于api数据动态加载不同的组件。在主页中,我有横幅和新闻部分。我不是要始终将标题的静态设计放在顶部,将新闻部分始终放在底部,而是要根据来自数据库的多次数据以及不同的数据加载横幅组件和新闻组件。 码: home.component.ts

import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { AccountServiceProvider} from '../../providers/account-service/account-service';

@Component({
    selector      : 'app-home',
    templateUrl   : './home.component.html',
    styleUrls     : ['./home.component.scss'],
    encapsulation : ViewEncapsulation.None
})
export class HomeComponent implements OnInit {

    public banner           : any;
    public news             : any;

    constructor( private accountService : AccountServiceProvider ) {
        /* data is coming from WordPress API; client can choose either banner first or news first */
        this.accountService.getStartPageData().then( ( response: any ) => {
            for ( let entry of response ) {
                if ( 'banner_block' === entry.acf_fc_layout ) {
                    this.banner = entry;
                }
                if ( 'news_block' === entry.acf_fc_layout ) {
                    this.news = entry;
                }
            }
        });
    }

    ngOnInit() {
    }
}

home.component.html

<app-banner [bannerData]="banner"></app-banner>
<app-news [newsData]="news"></app-news>

banner.component.ts

import { Component, OnInit, ViewEncapsulation, Input, EventEmitter, Renderer2 } from '@angular/core';

@Component({
    selector      : 'app-banner',
    templateUrl   : './banner.component.html',
    styleUrls     : [ './banner.component.scss' ],
    encapsulation : ViewEncapsulation.None
})

export class BannerComponent implements OnInit {

    @Input() bannerData : any;

    constructor( private renderer : Renderer2 ) {}

    ngOnInit() {
    }
}

news.component.ts

import { Component, OnInit, ViewEncapsulation, Input, EventEmitter, Renderer2 } from '@angular/core';

@Component({
    selector      : 'app-news',
    templateUrl   : './news.component.html',
    styleUrls     : [ './news.component.scss' ],
    encapsulation : ViewEncapsulation.None
})

export class NewsComponent implements OnInit {

    @Input() newsData : any;

    constructor( private renderer : Renderer2 ) {}

    ngOnInit() {
    }
}

现在,这里不是静态添加横幅和新闻的组件,而是要根据数据到达来加载该组件。 如何才能做到这一点 ?可以将html组件加载到ts文件中吗?如果是,怎么办?我仍在搜索解决方案,但到目前为止仍无济于事。

1 个答案:

答案 0 :(得分:1)

例如,您可以使用ngIf指令:

<div *ngIf="condition; then thenBlock else elseBlock"></div>
<ng-template #thenBlock><app-banner [bannerData]="banner"></app-banner></ng-template>
<ng-template #elseBlock><app-news [newsData]="news"></app-news></ng-template>

此处更多信息https://angular.io/api/common/NgIf