Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/31.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 如果else条件只有一次,如何执行*ngIf else?_Angular - Fatal编程技术网

Angular 如果else条件只有一次,如何执行*ngIf else?

Angular 如果else条件只有一次,如何执行*ngIf else?,angular,Angular,我使用*ngFor遍历div中的数组。在这个div中有另一个具有*ngIf else条件的div,其中else条件匹配25个值 我的问题是,不是25个值,而是只打印第一个值,而其他24个值应该隐藏或忽略。请注意,与if语句匹配的其他25个值都应该可见。这怎么可能 <div *ngFor="let item of messageArray; let index = index"> <div *ngIf="userids == item.userid;else other_co

我使用*ngFor遍历div中的数组。在这个div中有另一个具有*ngIf else条件的div,其中else条件匹配25个值

我的问题是,不是25个值,而是只打印第一个值,而其他24个值应该隐藏或忽略。请注意,与if语句匹配的其他25个值都应该可见。这怎么可能

<div *ngFor="let item of messageArray; let index = index">
  <div *ngIf="userids == item.userid;else other_content">{{item.username}}</div>
  <ng-template #other_content>{{item.username}}</ng-template>
</div>

您可以使用
first
操作符利用循环本身:



这里的*ngIf和*ngFor指令主要用于显示目的。如果您想提供任何逻辑,那么您应该避免在模板内这样做

在组件内拆分阵列,然后通过组件内的两个不同指令显示阵列

public otherElement: any = _.first(messageArray)
public filteredArray: any[] = _.filter(messageArray, item => item.id != otherElement.id)
您已经设置了“otherElement”和“FilterDarray”。 然后可以如下方式显示它们:

<div *ngFor="let item of filteredArray; let index = index">
  <ng-container>
    <div>{{item.username}}</div>
  </ng-container>
</div>
<ng-template #other_content>{{otherElement.username}}</ng-template>

{{item.username}
{{otherElement.username}
app.component.ts

constructor(private socketService : SocketserviceService) { 
  this.socketService.newMessageReceived().subscribe((data) => {
    this.messageArray = data.payload;
  });
};
userNamePrintInElse =""
constructor(private socketService : SocketserviceService) { 
  this.socketService.newMessageReceived().subscribe((data) => {
    this.messageArray.push(data);userids
    this.userNamePrintInElse = this.messageArray.filter(data => data.userid != this.userids )[0].username
  });
};
在Html中

<div *ngFor="let item of messageArray; let index = index">
  <div *ngIf="userids == item.userid">{{item.username}}</div>
</div>
  <div >{{userNamePrintInElse}}</div>

{{item.username}
{{userNamePrintInElse}

为什么不打印数组的第一个值?messageArray[0]但else codition 1st值如何可能?当您违反MVVM或MVC时会发生类似的情况。我会在ts文件中检查这件事。并返回一个布尔值show/notShow。然后将代码添加到ngIf中。在我看来,在html中编写这种逻辑毫无意义。是否要打印所有userid==item.userid;值,但用户ID!=item.userid第一个值?但是我想要的是如果条件所有值都只有其他条件第一个值,请用英语努力。我已经不太明白第一个问题了,但是这个评论很模糊。。。您的原始条件是什么?对不起,我的英语是*ngFor,在else条件中有50个值,25个值中有25个值,我只想打印else条件的第一个值OK,那么25个值存储在哪个其他变量中?在
messageArray
中有50个值,在if条件下有25个值,在else条件下有25个值。