Динамическая загрузка дочерних компонентов в Angular 5 - PullRequest
0 голосов
/ 31 августа 2018

Я хочу динамически загружать дочерние компоненты в угловые. Родительский компонент будет загружать дочерние компоненты в зависимости от некоторых условий.

Возможно ли, что мы определяем имена дочерних компонентов в файле машинописного текста родительского компонента, а в HTML мы используем интерполяцию строк для загрузки компонента?

Например, в машинописном тексте родительского компонента:

componentName = someCondition ? 'component1' : 'component2';

и в HTML

<app-{{componentName}}></app-{{componentName}}

Я пробовал это, но это не работает. Буду признателен за любую помощь в этом!

1 Ответ

0 голосов
/ 31 августа 2018

Первый подход:

<ng-container [ngSwitch]="componentName">
  <component-one *ngSwitchCase="'component1'"></component-one>
  <component-two *ngSwitchCase="'component2'"></component-two>
  ...
</ng-container>

Второй подход componentFactoryResolver

@Component({
    selector: 'parent',
    template: `
        <div #target></div>
    `
})
export class ParentComponent {
    @Input() child: string;
    @Input() value: string;

    //Get tag child component will be placed
    @ViewChild('target', { read: ViewContainerRef }) target: ViewContainerRef;
    private componentRef:ComponentRef<any>;

    //Child components
    private children = {
        child1: Child1Component,
        child2: Child2Component
    };

    constructor(private compiler: ComponentFactoryResolver) {}

    //Pass through value to child component
    renderComponent(){
        if (this.componentRef) this.componentRef.instance.value = this.value;
    }

    //Compile child component
    ngAfterContentInit() {
        let childComponent = this.children[this.child || 'child1'];
        //Resolve child component
        let componentFactory = this.compiler.resolveComponentFactory(childComponent);
        this.componentRef = this.target.createComponent(componentFactory);
        this.renderComponent();
    }

    //Pass through value to child component when value changes
    ngOnChanges(changes: Object) {
        this.renderComponent();
    }
}

Дочерние компоненты должны быть объявлены как Ввод компоненты

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...