且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在angular2中的模型更改时保持ui状态?

更新时间:2023-02-13 23:29:48

我们在工作中使用的模式是拥有一个公共变量,该变量指示是否加载了数据.我们称它为isLoaded. isLoaded初始化为false,并在数据来自可观察服务时设置为true.在您的HTML标记中,使用* ngIf仅在isLoaded设置为true后才显示数据.

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.

在我的工作中,当isLoaded为false时,我们还显示了一个动画加载器组件,以使用户知道系统正在等待某些东西,但这有点花哨.

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:

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>