2017-01-23 2 views
1

Я хочу предотвратить автоматическое выполнение компонентов при загрузке временной страницы. Я хочу выполнить компонент на основе нашего времени выбора.Как создать динамический динамический компонент 2?

Когда страница загружает компонент времени, выполняющий и добавляющий html-ответ на странице. Я не хочу его исполнять.

Проблема заключается в том, что «HeapMemoryComponent» выполняет и добавляет ответ html на странице во время загрузки страницы, прежде чем предпринимать какие-либо действия.

Я хочу, чтобы выполнить "HeapMemoryComponent" после того, как на основе выбора пункта

я говорил this code

routing.ts

import {ModuleWithProviders} from '@angular/core'; 
import {Router,RouterModule} from '@angular/router'; 
import {AppComponent} from './app.component'; 
import {HeapMemoryComponent} from './heap-memory/heap-memory.component' 
const appRoutes:Routes = [ 
{ 
    path: 'abc', 
    component: HeapMemoryComponent 
} 
]; 
export const routing:ModuleWithProviders = RouterModule.forRoot(appRoutes); 

LeftPanelComponent.ts

import { Component, OnInit } from '@angular/core'; 
import {LeftpanelService} from "../leftpanel.service" 
import {Leftpanel} from "../leftpanel"; 
import {MdDialog} from "@angular/material"; 
import {MdDialogRef} from "@angular/material"; 
import { Routes, RouterModule } from '@angular/router'; 
import {ServersListDialogComponent} from "../servers-list-dialog/servers-list-dialog.component"; 
@Component({ 
    selector: 'app-leftpanel', 
    templateUrl: './leftpanel.component.html', 
    styleUrls: ['./leftpanel.component.css'] 
}) 
export class LeftpanelComponent implements OnInit { 
    dialogRef: MdDialogRef<ServersListDialogComponent>; 
    leftpanels:Leftpanel[]; 
    receivedData:Array<any> = []; 

    constructor(
     public dialog: MdDialog,private service:LeftpanelService,public   router:Router 
    ) { } 

    ngOnInit() { 
    this.service.getLeftpanels().subscribe(lst =>this.leftpanels=lst); 
    } 

    transferDataSuccess($event) { 
    this.receivedData.push($event.dragData); 
    this.openDialog(); 
    } 
    openDialog() { 
     this.dialogRef = this.dialog.open(ServersListDialogComponent, { 
     disableClose: false 
    }); 

    this.dialogRef.afterClosed().subscribe(result => { 
    console.log('result: ' + result); 
    this.dialogRef = null; 
    if(result.componentName == "HeapMemoryComponent"){ 
     this.router.navigate(['HeapMemoryComponent']); 
    } 
    }); 
    } 

    } 

После нажатия на «Да» Я выполняю, как следующий компонент bas по выбору элементов.

HeapMemoryComponent

@Component({ 
selector: 'app-mainpanel', 
templateUrl: './heap-memory.component.html', 
styleUrls: ['heap-memory.component.css'] 
}) 
export class HeapMemoryComponent implements OnInit { 
constructor() { 
    console.log("HeapMemoryComponent object is created..."); 
} 

ngOnInit() {} 
} 

app.module.ts

import { BrowserModule } from '@angular/platform-browser'; 
import { NgModule } from '@angular/core'; 
import { FormsModule } from '@angular/forms'; 
import { HttpModule } from '@angular/http'; 
import { AppComponent } from './app.component'; 
import {HeapMemoryComponent} from './heap-memory/heap-memory.component' 

@NgModule({ 
declarations: [ 
AppComponent, 
LeftpanelComponent, 
RightpanelComponent, 
HeapMemoryComponent 
], 
imports: [ 
BrowserModule, 
FormsModule, 
HttpModule, 
MaterialModule.forRoot(), 
DndModule.forRoot(), 
routing 
], 
providers: [LeftpanelService,.....], 
bootstrap: [AppComponent], 
entryComponents:[ 
ServersListDialogComponent 
] 
}) 
export class AppModule { } 

Над HeapMemoryComponent есть HTML ответ и это выше компонент будет иметь службу. И у меня будет несколько компонентов, как указано выше.

Пожалуйста, дайте мне решение.

+0

Вы можете использовать '' ngIf', ngSwitch' или 'ViewContainerRef.createComponent()' http://stackoverflow.com/questions/36325212/angular-2- dynamic-tabs-with-user-click-selected-components/36325468 # 36325468 –

+0

@Gunter Zochbauer, где мне нужно добавить код? пожалуйста, помогите мне, я новичок в угловой. –

+0

Извините, вопрос слишком длинный. У меня нет времени, чтобы понять, в чем проблема. –

ответ

-1

Я использовал концепцию создания динамического компонента.

HeapMemoryComponent.ts

@Component({ 
selector: 'app-mainpanel', 
templateUrl: './heap-memory.component.html', 
styleUrls: ['heap-memory.component.css'] 
}) 
export class HeapMemoryComponent implements OnInit { 
id=0; 
constructor() { 
this.id = this.injector.get('id'); 
console.log("HeapMemoryComponent object is created..."); 
} 

ngOnInit() {} 
} 

LeftPanel.ts

import {Leftpanel} from "../leftpanel"; 
import {MdDialog} from "@angular/material"; 
import {MdDialogRef} from "@angular/material"; 
import { Routes, RouterModule } from '@angular/router'; 
@Component({ 
selector: 'app-leftpanel', 
templateUrl: './leftpanel.component.html', 
styleUrls: ['./leftpanel.component.css'] 
}) 
export class LeftpanelComponent implements OnInit { 
componentData = []; 
dialogRef: MdDialogRef<any>; 
leftpanels:Leftpanel[]; 
receivedData:Array<any> = []; 

constructor(
    public dialog: MdDialog,private service:LeftpanelService,public     router:Router 
) { } 

ngOnInit() { 
this.service.getLeftpanels().subscribe(lst =>this.leftpanels=lst); 
} 

transferDataSuccess($event) { 
this.receivedData.push($event.dragData); 
this.openDialog(); 
} 
openDialog() { 
    this.dialogRef = this.dialog.open(ServersListDialogComponent, { 
    disableClose: false 
}); 

this.dialogRef.afterClosed().subscribe(result => { 
console.log('result: ' + result); 
this.dialogRef = null; 
if(result.componentName == "HeapMemoryComponent"){ 
    this.componentData.push({ 
      component: HeapMemoryGraphComponent, 
      inputs: { 
      id: 5, 

      } 
     }); 
} 
}); 
} 

} 

Я назвал мой HeapMemoryComponent, если условие в нажимной метода() массива. Затем я добавил следующий код в html-файл, где хочу отобразить мой компонент. Рассмотрим я хочу, чтобы отобразить мой компонент в LeftPanel.html файл

LeftPanel.html

<dynamic-component *ngFor="let cd of componentData" [componentData]="cd"></dynamic-component> 

После этого я дал имя компонента динамического компонента создателя, чтобы создать компонент динамически.

динамические-component.ts

import {Component, Input, ViewContainerRef, ViewChild, ReflectiveInjector, ComponentFactoryResolver} from '@angular/core'; 
import {HeapMemoryGraphComponent} from '../heap-memory-graph/heap-memory-graph.component'; 

@Component({ 
selector: 'dynamic-component', 
entryComponents: [ 
HeapMemoryGraphComponent 
], // Reference to the components must be here in order to dynamically create them 
template: ` 
<div #dynamicComponentContainer></div> 
`, 
}) 
export default class DynamicComponent { 
currentComponent = null; 

@ViewChild('dynamicComponentContainer', { read: ViewContainerRef })  dynamicComponentContainer: ViewContainerRef; 

// component: Class for the component you want to create 
// inputs: An object with key/value pairs mapped to input name/input value 
@Input() set componentData(data: {component: any, inputs: any }) { 
if (!data) { 
    return; 
} 

// Inputs need to be in the following format to be resolved properly 
let inputProviders = Object.keys(data.inputs).map((inputName) => {return {provide: inputName, useValue: data.inputs[inputName]};}); 
let resolvedInputs = ReflectiveInjector.resolve(inputProviders); 

// We create an injector out of the data we want to pass down and this  components injector 
    let injector = ReflectiveInjector.fromResolvedProviders(resolvedInputs, this.dynamicComponentContainer.parentInjector); 

    // We create a factory out of the component we want to create 
    let factory = this.resolver.resolveComponentFactory(data.component); 

    // We create the component using the factory and the injector 
    let component = factory.create(injector); 

    // We insert the component into the dom container 
    this.dynamicComponentContainer.insert(component.hostView); 

    // We can destroy the old component is we like by calling destroy 
    if (this.currentComponent) { 
    //this.currentComponent.destroy(); 
    } 

    this.currentComponent = component; 
} 

    constructor(private resolver: ComponentFactoryResolver) { 

} 
} 
Смежные вопросы