how to maintain ui state on model change in angular2?

前端 未结 1 734
伪装坚强ぢ
伪装坚强ぢ 2021-01-29 05:45

what is the best way to maintain UI state in angular2? currently i am having problem within single component.

so i am trying to maintain class using ngif but dont know

相关标签:
1条回答
  • 2021-01-29 06:06

    The pattern we've been using at my job is to have a public variable that indicates whether data is loaded. Let's call it isLoaded. isLoaded is initialized to false, and set to true when the data comes from your observable service. In your HTML markup, use *ngIf to only show the data after isLoaded is set to true.

    At my job, we also show an animated loader component when isLoaded is false, to let the user know the system is waiting on something, but that is getting a little fancy.

    To implement this approach in your code, you would do something like:

    TypeScript/Javascript:

    public isLoaded: boolean = false;
    
    ...
    
    ngInit(): void {
        this.ObservableService.getData.subscribe((val) => {
            this.data= val;
            this.isLoaded = true;
        });
    
        ...
    }
    

    HTML:

    <div *ngIf="!isLoaded">
        Loading Data ...
    </div>
    <div *ngIf="isLoaded">
        <div *ngFor="let foo of data">
            <div class="collapsible-header" [id]="foo.array1.value1">
                {{poo.array1.value2}} , <h6>posted on {{foo.array1.value3}}</h6>
            </div>
            <div class="collapsible-body">
                <p>{{foo.array2.value2}}</p>
            </div>
            <ul class="collection">
                <li *ngIf="foo.array4.value1>= 1" class="active collection-item">
                    <div *ngFor="let p of foo.array4">
                        <span class="title">{{p.somevalue}}</span>
                    </div>
                </li>
             </ul>
             <div>
                    <input type="text" (ngModel)="mymodel.value1" ">
                    <button type="submit" (click)="callback(mymodel)">Submit</button>
             </div>
        </div>
    </div>
    
    0 讨论(0)
提交回复
热议问题