【问题标题】:How to set a value of a property of a nested item in order to make it visible via *ngIf directive如何设置嵌套项的属性值以使其通过 *ngIf 指令可见
【发布时间】:2020-03-23 23:32:31
【问题描述】:

我创建了一个组件来重用角材料中的 mat-progress-spinner。我需要这个以避免为每一页放置相同的代码。这是有效的代码:

<div id="overlayProgressSpinner">
    <div class="center">
    <mat-progress-spinner
        style="margin:0 auto;"
        mode="indeterminate"
        diameter="100"
        *ngIf="loading">
    </mat-progress-spinner>
    </div>
</div>

这很简单。仅将“加载”设置为真或假。 我做了什么?

我将上面的代码放在一个自定义组件中。现在是这样的:

<app-progress-spinner></app-progress-spinner>

其HTML代码相同,其TS代码如下:

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

@Component({
  selector: 'app-progress-spinner',
  templateUrl: './progress-spinner.component.html',
  styleUrls: ['./progress-spinner.component.scss']
})
export class ProgressSpinnerComponent implements OnInit {
  loading = false;
  constructor() { }

  ngOnInit() {
  }

  public isLoading(value: boolean) {
    this.loading = value;

  }

  public changeSpinnerCSSClass() {
    const htmlDivElement = (window.document.getElementById('overlayProgressSpinner') as HTMLDivElement);
    if (this.loading) {
      htmlDivElement.className = 'overlay';
    } else {
      htmlDivElement.className = '';
    }
  }

}

当“loading”属性属于当前组件时,我可以显示和隐藏“mat-progress-spinner”组件。否则,当它属于“app-progress-spinner”时,它已设置但未显示。我试图使其可见的代码如下:

          this.progressSpinner.isLoading(false); // it is set, but it does not work.
          this.progressSpinner.changeSpinnerCSSClass(); // it works

如果后面的逻辑属于当前组件,则似乎无法使用该方法设置 *ngIf="loading"。

如何做到这一点?

【问题讨论】:

    标签: javascript angular typescript angular-material


    【解决方案1】:

    您需要在您的ProgressSpinnerComponent 中创建一个input。为此,请在属性 loading 之前添加 @Input() 装饰器:

    import { Component, OnInit, Input } from '@angular/core';
    
    @Component({
      selector: 'app-progress-spinner',
      templateUrl: './progress-spinner.component.html',
      styleUrls: ['./progress-spinner.component.scss']
    })
    export class ProgressSpinnerComponent implements OnInit {
     @Input() loading = false;
    

    因此,您需要在任何地方使用app-progress-spinner

    <app-progress-spinner [loading]="loading"></app-progress-spinner>
    

    注意:分配给输入loadingloading变量属于包含app-progress-spinner的组件。

    这是因为每个组件都有自己的范围,这意味着它无法访问外部世界,除非您创建 inputoutput 以接收或发送数据。还有 ngModel 可以用于双向数据,但在大多数情况下不推荐。

    【讨论】:

    • 谢谢。它已编译,但是当我尝试将其设置为 true 或 false 时,什么也没有发生。如何以使其可见或隐藏的方式这样做?
    • 你不需要使用 isLoading() 方法,实际上它不会起作用。您需要通过修改加载输入值来改变加载状态。使用&lt;app-progress-spinner [loading]="true"&gt;&lt;/app-progress-spinner&gt; 应该会显示一个进度微调器。如果没有,您需要仔细检查您的代码是否有问题。
    • 是的。我发现了这个问题。我试图更新以直接更改父组件的属性值,而不是将其属性值与装饰器一起使用。可以查看您的答案,以明确“app-progress-spinner”声明的“加载”变量来自当前组件,而不是来自父组件。我知道了。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2021-11-15
    • 2021-11-21
    • 2013-10-26
    • 2010-10-24
    • 1970-01-01
    • 2017-02-06
    • 2011-08-25
    • 1970-01-01
    相关资源
    最近更新 更多