【问题标题】:Is it possible to put an ngFor inside an ngIf?是否可以将 ngFor 放入 ngIf 中?
【发布时间】:2017-12-17 23:10:32
【问题描述】:

我两天以来一直在尝试解析一个 Json 文件,其中包含嵌套对象,其中包含自己在 ngIf 中的对象...我认为代码会更加明确:

所以想象这是一个子组件有条件地从来自按钮的父事件中打开:

我的 http 服务正在运行,因为我已经在其他一些组件中使用了它,并且 observable 是“user3”

父级html:

    <div class="parent">
        <img src="fold_down_black.png" type="button"(click)="toggleChild()"/>
    <div><my-child [showMePartially]="showVar" ></my-child></div>
    </div>

我在 child.ts 中使用如下输入绑定它:

      @Input() showMePartially: boolean;

这是 child.html:

 <div *ngIf="showMePartially" class="child" >
   <span id="tfonc" *ngFor="let user3 of userService3.users3 | async">Fonctionnal duration : {{user3.data.operating_rate}}%
   </span>
</div>

这是我的服务:

 export interface User3 {
 data: any;
}
   const usersURL = 'http://my.supa.json;php';

@Injectable()
export class UserService3 {

  users3: Observable<User3[]>;

    constructor (public http: Http) {


          getData() {

     const tick3$ = Observable.timer(100, 60000);

     return tick3$.flatMap(() => this.http.get(usersURL)).map(res => 
res.json());   // .publishBehavior(<User3[]>[]).refCount();

当我在视图中什么也没有做,控制台中也什么都没有做时...提前感谢您的帮助..我想冲突来自 ngIf 内的 ngFor...

【问题讨论】:

  • 您正在尝试循环观察。在您的 child.ts 中订阅它,并将发出的数据分配给一些初始值为 [] 的新道具,然后循环遍历它。或者,从 4.x 开始,您可以使用 async 管道:angularjs.blogspot.com.by/2017/03/…
  • @wostex 是的,我也想使用异步管道我更新我的帖子...我很难订阅它,因为我注入了已经在我的构造函数中订阅的 userService,例如:构造函数( public userService3: UserService3) { } ngOnInit() { } } ...对吗?
  • @wostex 我是否应该再次订阅,例如:public ngOnInit () { this.dataSubscription = this.userService3 (if dataSubscription: Subscription;)
  • users3 是订阅还是可观察的?如果它是可观察的,你需要在你的组件中订阅它。服务注入与它无关。
  • @wostex users3 是一个 Observable 你是对的,所以我不需要在构造函数中注入我的服务?我不知道...我也用我的服务更新了我的帖子

标签: angular typescript rxjs ngfor angular-ng-if


【解决方案1】:

我相信问题是你试图循环通过 users3 observable。您需要在 child.ts 中订阅它。在您的 Child 类中:

myUsers = [];
sub: Subscription;

// inject a service. don't forget to import userService3 also
constructor(private userService: userService3) {}  

ngOnInit() {
    this.sub = this.userService.users3.subscribe(users => this.myUsers = users) // subscribe!
}
ngOnDestroy(){
    this.sub.unsubscribe();
}

在您的模板中:

*ngFor="let user3 of users3 

【讨论】:

  • @EmileCantero 我已经对其进行了一些编辑,以便您可以看到道具之间的差异。
  • 感谢您的帮助,听起来您的代码在控制台中返回了任何错误,但我的视图中仍然没有任何内容..奇怪...从您的角度来看也不应该使用 ngOndestroy 作为所以? ngOnDestroy() { if (this.users3) { this.users3.unsubscribe(); } }
  • @EmileCantero 你说得对,这里需要 onDestroy 但这不是问题的重点。它现在应该可以工作了;我唯一能想到的是你的 users3 observable 没有发出任何东西或没有正确实施。
  • 是的,我认为它也应该工作..也许它是关于 css 或 html..我会让你知道,因为我有很多嵌套的子组件(可能是 z-index 属性......)
猜你喜欢
  • 2022-11-03
  • 1970-01-01
  • 1970-01-01
  • 2020-09-05
  • 2021-08-03
  • 1970-01-01
  • 2022-11-24
  • 1970-01-01
  • 2019-03-06
相关资源
最近更新 更多