簡體   English   中英

加載和卸載angular6組件

[英]Load and unload angular6 component

我試圖在單擊圖像時創建圖像模態。 我已經設置好了,以便在單擊圖像時加載子組件。 問題在於,它只能被單擊一次,並且在關閉后將其設置為display: none

可以通過單擊子組件中的關閉按鈕來關閉它。 但是我只能通過display: none做到這一點display: none CSS中display: none ,使該組件不可見,但仍處於活動狀態。

我最終想要的是一種在按下關閉按鈕時卸載該子組件的方法。 或設置opacity: 1再次單擊父級中的圖像時。

HTML父級:

<app-image-modal
    *ngIf="clicked"
    [slice] = "slice"
    [clicked] = "clicked">
</app-image-modal>

<img src"img.png" (click)="imageClicked()"/>

TS家長:

export class ImageComponent {
public clicked = false;

public imageClicked() {
    this.clicked = true;
}
}

HTML子級:

<section [ngClass]="{'hide': hide}">
  <div [ngClass]="{'active': show}">

    <img src"img.png" />

    <div class="close" (click)="hideModal()">
        <button>X</button>
    </div>

  </div>                                                              
</section>

TS孩子:

export class ImageModalComponent implements OnInit {
public show = false;
public hide = false;

@Input() clicked: boolean;

public ngOnInit() {
    this.show = true;
}

public hideModal() {
    this.show = false;
    this.hide = true;
}
}

我認為您的組件溝通很落后

結束信息應從孩子到父母。 要實現此目的:您可以在子組件中有一個EventEmitter,然后從父組件中監聽它。

然后,如果要卸載子組件,則可以在父模板的子組件中使用帶*ngIf的布爾值。

顯示或不顯示模式的事實應在父級別處理(例如:不需要布爾值在子級中顯示和隱藏,順便說一句,您可以只使用一個布爾值而不是兩個布爾值來處理)。

為什么在父母一級? 因為您要卸載組件,而不僅僅是隱藏它。

代碼示例:

**在子組件**中:

export class ImageModalComponent implements OnInit {
    @Output() close = new EventEmitter();

    public hideModal() {
        this.close.emit(); // here we tell the parent that the "close" button has been clicked.
    }
}

在子HTML中,刪除所有依賴於“ show”和“ hide”的內容(假定顯示了該組件):

<section>
  <div class="active">
  ...

**在父模板中:**

export class ImageComponent {

    public clicked = false;

    public imageClicked() {
        this.clicked = true;
    }

    public childCloseEventHandler(): void {
        this.clicked = false; // this will trigger the unload of the child, since you have `*ngIf="clicked"` for the child component
    }
}

HTML父級:

<app-image-modal
    *ngIf="clicked"
    [slice]="slice"
    (close)="childCloseEventHandler()">   <!-- I changed this line -->
</app-image-modal>

<img src"img.png" (click)="imageClicked()"/>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM