2017-01-11 4 views
0

В моем Угловом 2 приложении I отображение списка компонентов, как это (после выполнения * ngFor):Угловая система 2 обзора: реализация повторы

app.component.html

<my-example-component></my-example-component> // 1 
<my-example-component></my-example-component> // 2 
<my-example-component></my-example-component> // 3 
<my-example-component></my-example-component> // 4 
<my-example-component></my-example-component> // 5 

мой-example.component.html:

<h1>{{title}}</h1> // juste as example 
...... 
<button>Click ME</button> 

что я хотел бы сделать, чтобы сделать это, когда я нажимаю на «жми меня» в компоненте myExample, я хотел бы отобразить другой компонент (текстовую область). Только ниже данного компонента myExample, на который я нажимаю.

EDIT

Это для системы обзора, и компонент Я хочу, чтобы отобразить ниже myexampleComponent (который является единственным рецензия) является переигровка для этого обзора.

ответ

0

Вот как я бы это сделать:

определяют в качестве родительского компонента: showIndex = null; и установить его в нуль, если вы хотите, чтобы скрыть его снова.

родительский вид компонента:

<div template="ngFor let item of [1,2,3,4,5]; let i = index;"> 
<my-example-component (onShowMore)="showIndex = i"></my-example-component> 
    <div *ngIf="showIndex === i">More stuff in here</div> 
</div> 

MyExampleComponent:

@Component({ 
    selector: 'my-example-component', 
    template: `<div style="border: 1px solid salmon"><button (click)="onShowMore.emit(null)">Show More</button></div>` 
}) 

export class MyExampleComponent 
{ 
    @Output() onShowMore = new EventEmitter<any>(); 
} 

Редактировать Как переключать материал в детском компоненте (код не тестировался):

import {Component, Output, EventEmitter, Input} from "@angular/core" 

@Component({ 
    selector: 'Parent', 
    template: `<child *ngFor="let item of [1,2,3,4,5]; let i = index;"(onShowMore)="onShowMore($event)" [index]="i" [showIndex]="showIndex"></child>` 
}) 

export class ParentComponent 
{ 
    private showIndex: number | null; 

    ngOnInit() 
    { 
     this.showIndex = null; 
    } 

    onShowMore(childIndex) 
    { 
     this.showIndex = childIndex 
    } 
} 


@Component({ 
    selector: 'child', 
    template: ` 
      <div> 
       <button (click)="showIndex === index ? hide() : show()"> 
       {{showIndex === index ? 'Hide me' : 'Show me'}} 
       </button> 
      </div> 
      <div *ngIf="showIndex === index">This is more content</div> 
      ` 
}) 

export class ChildComponent 
{ 
    @Input() showIndex: number | null; 
    @Input() index: number; 
    @Output() onShowMore = new EventEmitter<number | null>(); 


    show() 
    { 
     this.onShowMore.emit(this.index); 
    } 

    hide() 
    { 
     this.onShowMore.emit(null); 
    } 
} 
+0

проблема в том, что мой комментарий компонент ВНУТРИ моей-exampleComponent и не в родителе, как вы сделали –

+0

Отлично! наконец, после перемещения кода в работе! thx –

+0

Да, не проблема, собирался сказать, что вы можете просто пройти в индексе 2 и сделать проверки внутри дочернего компонента. Отметьте как правильно, если это вам помогло. –

1

DEMO: https://plnkr.co/edit/NzVUHpT7WQWPB2mmUlJM?p=preview

Вы должны использовать componentFactoryResolver добавить (component) динамически myexamplecomponent

/*-----------comment Component start--------*/ 
@Component({ 
    selector: 'comment', 
    template: `<textarea cols="20" rows="5">Hi</textarea>` 
}) 
export class comment{} 

/*-----------comment Component end--------*/ 

/*-----------my-example-component Component start--------*/ 
@Component({ 
    selector: 'my-example-component', 
    entryComponents: [comment], 
    template: `<div #target> Child {{n}} 
     <button (click)="clickMe()">Add Comment</button> 
    </div>` 
}) 

export class MyExampleComponent{ 
    @Input() n: number; 

    @ViewChild('target', {read: ViewContainerRef}) target: ViewContainerRef; 
    cmpRef: ComponentRef<comment>; 
    private isViewInitialized:boolean = false; 

    constructor(private componentFactoryResolver: ComponentFactoryResolver, private compiler: Compiler, 
     private cdRef:ChangeDetectorRef) {} 


    clickMe() { 
    let factory = this.componentFactoryResolver.resolveComponentFactory(comment, 2); 
    this.cmpRef = this.target.createComponent(factory) 
    //this.cmpRef.instance.n = 'foobar'; 
    //this.cdRef.detectChanges(); 
    } 
} 

/*-----------my-example-component Component end--------*/ 
+0

Не понимаю ваш вопрос ... – micronyks

+0

Зачем отвечать тогда? –

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