2017-07-27 29 views
0

我想在主機組件中使用雙向綁定變量來維護模態的狀態。因此,<my-modal [(isOpen)]="isModalOpen"></my-modal>應該工作。在Angular中雙向綁定模態的布爾值

爲此,我在模態組件中添加了一個事件發射器:@Output() isOpenEvent: EventEmitter<boolean> = new EventEmitter<boolean>(false)。另一個屬性是布爾本身@Input() isOpen: boolean = false;。存在執行以下操作的函數close()this.isOpen = false; this.isOpenEvent.emit(false)。 HTML中的按鈕稱爲close()函數。

主機組件具有自己的局部變量,當調用模態的close()函數時,該變量有望更新。

我在做什麼錯?

+1

嘗試改變'isOpenEvent'用' isOpenChange' – echonax

+0

嗨,我想讀更多關於這個。你能把我和文件聯繫起來嗎? –

+0

該文檔沒有明確說明這一點:-)它通過結合兩個你得到的[[(ngModel)]雙向綁定,給出了一個使用'[ngModel]'和'(ngModelChange)'的例子。如果問題解決了,我可以提供它作爲答案。 – echonax

回答

1

您的isOpenEvent應該是isOpenChange以便雙向綁定工作。

括號[]表示屬性綁定,而知識庫()是事件綁定,如你所知。事件綁定應該以Change結尾,以便同名雙向綁定起作用。

我知道文檔「隱藏」這一寶貴的信息,但檢查線路

的雙向綁定語法,實際上是屬性綁定和事件的結合只是語法糖。角desugars的SizerComponent結合成這樣:

在docs

https://angular.io/guide/template-syntax#two-way-binding---


TL;博士

[isOpen] + (isOpenChange) = [(isOpen)]

0

當你從模態組件中發出事件時,我沒有在你的代碼片段中看到在父組件中調用的函數。

在父HTML你應該有這樣的事情:

<app-modal (emitter)="receiveDataFromChild($event)"></app-modal> 

,並在父母的.ts文件這樣的:

import { Component, OnInit, ViewChild } from '@angular/core'; 
import { ChildComponent } from './modal-component'; 

@Component({ 
    selector: 'app-parent-component', 
    templateUrl: './parent.component.html', 
    styleUrls: ['./parent.component.css'] 
}) 

export class ParentComponent implements OnInit { 

    private isOpen = false; 
    // ******** Get reference of child component ****** 
    @ViewChild(ChildComponent) child : ChildComponent ; 

     constructor() {} 

     ngOnInit() { } 

     receiveDataFromChild(data) { 
      this.isOpen = data; 
     } 
} 

看看:this answer

希望這幫助!