2017-05-19 76 views
0

我有一個像這樣的ngFor。更改動態組件角度2上的內容

<div *ngFor="let object of objects; let i = index" class="discover__col"> 

與像變薄

<a (click)='onOpen(object)'>Details</a> 

事件結合我有一個動態的模式是這樣的。

dynamicModal(object): void { 
    const modal$ = this.modalService.create(SharedModule,  DynamicModalComponent, { 
     title: object.title, 
     desc: object.desc 
    } 

我得到瓷磚和遞減是不確定的。

如何傳遞我在ngFor循環中迭代的對象?

ModalService

@Injectable() 
export class ModalService { 
    private vcRef: ViewContainerRef; 
    private injector: Injector; 
    public activeInstances = 0; 

    constructor(private compiler: Compiler) { 
    } 

    registerViewContainerRef(vcRef: ViewContainerRef): void { 
    this.vcRef = vcRef; 
    } 

    registerInjector(injector: Injector): void { 
    this.injector = injector; 
    } 

    create<T>(module: any, component: any, parameters?: Object): 
Observable<ComponentRef<T>> { 
    const componentRef$ = new ReplaySubject(); 
    this.compiler.compileModuleAndAllComponentsAsync(module) 
    .then(factory => { 
    const componentFactory = factory.componentFactories.filter(item => item.componentType === component)[0]; 
    const childInjector = ReflectiveInjector.resolveAndCreate([], this.injector); 
    const componentRef = this.vcRef.createComponent(componentFactory, 0, childInjector); 
    Object.assign(componentRef.instance, parameters); // pass the @Input parameters to the instance 
    this.activeInstances ++; 
    componentRef.instance["componentIndex"] = this.activeInstances; 
    componentRef.instance["destroy"] =() => { 
     this.activeInstances --; 
     componentRef.destroy(); 
    }; 
    componentRef$.next(componentRef); 
    componentRef$.complete(); 
    }); 
return <Observable<ComponentRef<T>>> componentRef$.asObservable(); 
    } 
} 

端服務

這是一個對象{ 'title':'test', 'desc':'test2', }

這是父

<objects [objects]='objects' (open)='objectModal(object)'></objects> 

這是子組件

<div *ngFor='object of objects'> 
    <object-component (click)='onOpen(object)'></object-component> 
</div> 

@Output() open: EventEmitter<Object> = new EventEmitter<Object>(); 

onOpen(object) { 
    this.open.emit(object); 
} 

,如果我做title: 'test', title: 'test2'

它工作正常。

但是,我需要從被點擊的ngFor對象中獲取信息。基本上,我不是如何將信息傳遞給父項,而不是索引,而是實際的對象本身。所以我可以做到這一點,它不是沒有定義。

title: service.title, 
title: service.desc, 
+0

您可以發佈模態服務代碼,並且該對象是否具有標題和desc屬性? – mikias

+0

是的,這些屬性存在 –

+0

你有'onOpen(object)'處理程序,但你顯示'dynamicModal'函數的代碼。他們有什麼關係? – lbrahim

回答

0

我懷疑你在這段代碼

<objects [objects]='objects' (open)='objectModal(object)'></objects> 

或者更準確地說犯的錯誤,在這裏

(open)='objectModal(object)' 

應該

(open)='objectModal($event)' 

Plunker Example

+0

答案有幫助嗎? – yurzui