2017-10-08 55 views
0

我有4個組成部分,應該讓一類「裝」,當他們準備好了,但我不太知道如何在一個不錯的方式處理這一角2加載的類

的compoenents不是一個ngFor,所以他們沒有索引。

<div class="component" [ngClass]="{'loaded': loaded1}">1 </div> 
<div class="component" [ngClass]="{'loaded': loaded2}">2 </div> 
<div class="component" [ngClass]="{'loaded': loaded3}">3 </div> 
<div class="component" [ngClass]="{'loaded': loaded4}">4 </div> 

..

在我的課,我有一個4個屬性。但是,這真的是一個很好的方式,或者是更好/更容易。我寧願只擁有1個loaded屬性,影響的組件單獨

export class test { 
    public loaded1 = false; 
    public loaded2 = false; 
    public loaded3 = false; 
    public loaded4 = false; 

methodForComponent1() { 
    this.loaded1 = true; 
} 
methodForComponent2() { 
    this.loaded2 = true; 
} 
methodForComponent3() { 
    this.loaded3 = true; 
} 
methodForComponent4() { 
    this.loaded4 = true; 
} 

} 

SD

+0

如果您的標準角度生命週期加載時,您可以簡單地創建單獨的組件,前提是它具有不同的模板或類似組件。並在該組件的模板中添加一個類。然後,如果您需要在從父組件加載後處理此組件,則可以使用輸出處理事件。我在示例中添加了如何在答案中完成所有這些操作。由於您將功能分爲不同的組件,因此對您更好。可以更好地封裝它並在未來擴展功能。 –

回答

0

您可以使用對象與數爲布爾。

加載= {}

+0

您能舉一個例子嗎 – Johansrk

0

您可以爲這四個部分,如果你添加生命週期掛鉤的一個,那個叫ngAfterViewInit()一個組成部分。你可以閱讀關於這個there。然後,在這個組件,你可以發射這樣的事情創建輸出事件:

import { Component, Output, EventEmitter } from '@angular/core'; 

@Component({ 
    selector: 'your-compoent', 
    template: '<div [ngClass]="{'loaded': loaded}>Your template</div>' 
}) 
export class YourComponent { 
    private loaded:boolean = false; // this for your class 
    @Output() componentLoaded = new EventEmitter(); 

    ngAfterViewInit() { 
    this.loaded = true; 
    this.componentLoaded.emit(this.user); //there you emmit your paren component about that your component loaded 
    } 
} 

您的括號組成的模板仍然可以看起來像你的樣品中,但添加事件處理:

<your-component (componentLoaded)="yourFunctionInParentComponent($event)"></your-component>// you can add so many component so you need 

,然後在你的父組件,你需要添加功能處理該事件

yourFunctionInParentComponent(event){ 
//there you can do what you need 
} 

關於輸出並處理,你可以閱讀更多there

+0

如果沒有父母組件 – Johansrk