标题重写为:我的div或其数据未被ngFor指令正确渲染
P粉450744515
P粉450744515 2023-09-06 21:15:27
[HTML讨论组]

我在我的组件中创建了一个我订阅的服务,但是当我使用ngFor时,div根本不渲染。

Component.TS文件

import { Component, OnInit } from '@angular/core';
import {FormBuilder, Validators} from '@angular/forms';
import { PlansService } from 'src/app/services/plans.service';


interface JobType {
  value: string;
  viewValue: string;
}

interface WorkEnv {
  value: string;
  viewValue: string;
}


@Component({
  selector: 'app-post-job',
  templateUrl: './post-job.component.html',
  styleUrls: ['./post-job.component.css']
})

export class PostJobComponent implements OnInit {

  jobTypes: JobType[] = [
    {value: 'type-0', viewValue: '全职'},
    {value: 'type-1', viewValue: '兼职'},
    {value: 'type-2', viewValue: '自由职业'},
 
  ];

  workEnvs: WorkEnv[] = [
    {value: 'type-0', viewValue: '远程'},
    {value: 'type-1', viewValue: '混合'},
    {value: 'type-2', viewValue: '现场'},
 
  ];

  jobForm = this.fb.group({ 

    jobTitle: this.fb.group({
      title: ['', [Validators.required, Validators.minLength(2), Validators.pattern('^[_A-z0-9]*((-|\s)*[_A-z0-9])*$')]],
      jobType: ['', [Validators.required]]
    }),

   })

   plans: any;
  
  constructor(private fb: FormBuilder, private service:PlansService) {
   }

  ngOnInit(): void {

    this.service.getPlans()
      .subscribe(response => {
        this.plans = response;
        console.log(response);
      });
    
  }



   // Getter method to access formcontrols
   get myForm() {
    return this.jobForm.controls;
  }

 
  // Submit Registration Form
  // onSubmit() {
  //   this.submitted = true;
  //   if(!this.jobForm.valid) {
  //     alert('Please fill all the required fields to create a super hero!')
      
  //   } else {
  //     console.log(this.jobForm.value)
  //   }
  // }

}

Component.html文件

<div class="subscription-container" >
  <div class="card" *ngFor="let plan of plans " >
      <h1>{{plan.title}}</h1>
  </div>
</div>

数据在我的console.log中显示,但在卡片上根本没有渲染。请帮忙,谢谢!

我尝试在ts文件中添加了一个虚拟数组,并将其打印到控制台日志中,但仍然没有在div中渲染。

P粉450744515
P粉450744515

全部回复(1)
P粉785522400

您可以异步加载您的计划。

  1. 创建一个可观察对象 public plans$: Observable<any>

  2. 分配您的订阅 this.plans$ = this.service.getPlans();

  3. 在您的HTML中有条件地渲染

<ng-container *ngIf="plans$ | async as plans">
 <div *ngFor="let plan of plans">
  {{ plan | json }} 
 </div>
</ng-container>
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号