繁体   English   中英

如何过滤 Angular 中的 class?

[英]How to filter a class in Angular?

我试图在列表中显示其方法“arduino”等于 true(它是一个布尔值)的项目。

我尝试在同一行执行 *ngFor 和 *ngIf 但它给出了错误,因此在另一行执行此操作时,系统会加载方法“arduino”也等于“false”的项目,所以它不会运作良好

如何从 component.ts 过滤它,以便仅加载具有方法 project.arduino = true 的项目?

这是component.ts中的代码

@Component({
  selector: 'app-arduino-projects',
  templateUrl: './arduino-projects.component.html',
  styleUrls: ['./arduino-projects.component.css'],

  providers: [ProjectService]

})
export class ArduinoProjectsComponent implements OnInit {

  public projects: Project[];
  public url: string;

  constructor(
    private _projectService: ProjectService
  ) {
    this.projects = [];
    this.url = Global.url;
   }

  ngOnInit(): void {
    this.getProjects();
  }

  getProjects(){
    this._projectService.getProjects().subscribe(
      response => {
        if(response.projects){
          this.projects = response.projects; **************** this is the property that I have to filter and I don't know how to do it
        }
      },
      error => {
        console.log(error)
      }
    )
  }

这是component.html中的相关代码

<div class="project-list">
        <ul>
            <li *ngFor="let project of projects" class="project">
              <ng-container *ngIf="project.arduino == true"> ************ Here i filtered it in that way
                    <a [routerLink]="['/project', project._id]">
            
                    <div class="image-box">
                        <div class="image">
                        <img src="{{ url+'get-image/'+project.imagefront }}" *ngIf="project.imagefront" />
                        </div>
                    </div>
                  </a>
              </ng-container>
            </li>
        </ul>
      </div>

通过这种方式,它正在加载 project.arduino = false 的项目,它不会在屏幕上显示它们,但会弄乱浏览器中的列表

我正在使用 Angular 13

非常感谢!

您可以将*ngFor移动到<ng-container>而不是*ngIf 然后将*ngIf移动到<li>标记。 确保只有那些<li>在条件为true的 DOM 中。

<div class="project-list">
  <ul>
    <ng-container *ngFor="let project of projects">
      <li *ngIf="project.arduino == true" class="project">
        <a [routerLink]="['/project', project._id]">
          <div class="image-box">
            <div class="image">
              <img src="{{ url+'get-image/'+project.imagefront }}" *ngIf="project.imagefront" />
            </div>
          </div>
        </a>
      </li>
    </ng-container>
  </ul>
</div>

我认为如果方法“arduino”是 boolean 你只需要做类似的事情:

<ng-container *ngIf="this.project.arduino">

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM