2016-08-29 66 views
1

我试图在单个页面上多次使用引导弹出组件作为嵌套组件。此弹出组件采用与@Input()不同的值。问题是,页面上的每个弹出窗口都具有与最后一个弹出窗口相同的值。那么,我怎样才能获得同一个嵌套组件的多个实例呢?angular2 - 在单个父组件中多次使用具有不同输入的嵌套组件的相同组件

这里是父组件:

@Component({ 
    selector: 'my-parent', 
    templateUrl: 'app/components/parent/parent.component.html', 
    directives: [PopupDirective] 
}) 
export class ParentComponent { 
    private doSomething() { 
     // do something 
    } 
} 

这是我的父组件的HTML:

<button class="btn btn-success" 
     (click)="popup1.show()">Call Popup 1</button> 

<button class="btn btn-success" 
     (click)="popup2.show()">Call Popup 2</button> 

<my-popup #popup1 
      [id]="1" 
      [title]="Popup 1" 
      [body]="This is my test popup 1" 
      (confirmation)="doSomething()"></my-popup> 

<my-popup #popup2 
      [id]="2" 
      [title]="Popup 2" 
      [body]="This is my test popup 2" 
      (confirmation)="doSomething()"></my-popup> 

这里是弹出组件:

@Component({ 
    selector: 'my-popup', 
    templateUrl: 'app/directives/popup/popup.directive.html' 
}) 
export class PopupDirective { 

    @Input() id: string; 

    @Input() title: string; 
    @Input() body: any; 

    @Output() confirmation: EventEmitter<string> = new EventEmitter<string>(); 

    private triggerPopup: string; 

    constructor() { 
     this.triggerPopup = "triggerPopup"; 
    } 

    confirm() { 
     this.confirmation.emit('Click from nested component'); 
    } 


    show() { 
     document.getElementById(this.triggerPopup).click(); 
    } 
} 

最后的HTML我弹出的代码

<a id="{{ triggerPopup }}" 
    href="#popup{{ id }}" 
    data-toggle="modal" 
    [hidden]="true"></a> 

<div class="modal fade" id="popup{{ id }}" role="dialog"> 
    <div class="modal-dialog"> 
     <div class="modal-content"> 
      <div class="modal-header"> 
       <h4>{{ title }}</h4> 
      </div> 
      <div class="modal-body"> 
       <div>{{ body }}</div> 
       <div style="clear: both;"></div> 
      </div> 
      <div class="modal-footer"> 
       <a class="bin ban-default" 
        data-dismiss="modal"> 
        Close</a> 

       <a class="bin ban-success" 
        data-dismiss="modal" 
        (click)="confirm()"> 
        Confirm</a> 
      </div> 
     </div> 
    </div> 
</div> 

回答

1

您分配相同的ID给每个元素

constructor() { 
    this.triggerPopup = "triggerPopup"; 
} 

,因此

document.getElementById(this.triggerPopup).click(); 

总能找到,因为它搜索整个页面,不关心组件边界的第一个。

我建议你使用模板变量和@ViewChild()代替

<a #triggerPopup" 
export class PopupDirective { 
    @ViewChild('triggerPopup') triggerPopup:ElementRef; 

    show() { 
    this.triggerPopup.nativeElement.click(); 
    } 
+0

好吧,那是合乎逻辑的。但它并没有解决它。我认识到''href =“#popup {{id}}”'总是只是'#popup'。我可以像上面的回答一样做,但是如何通过引导框架触发弹出窗口?我不能只是做'href =“#popup {{id}}”',因为这个url就像'/#popup [Object]'。 – user2741109

+0

我建议使用不同于'id'的输入属性名称。 'id'是'Element'的一个属性。 –

+0

谢谢,现在它正在工作。 – user2741109

相关问题