簡體   English   中英

ngFor 指令沒有呈現我的 div 或其數據

[英]ngFor directive is not rendering my div or its data

我在我的組件中創建了一個我訂閱的服務,但是,當我使用 ngFor 時,div 根本沒有呈現。

組件.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: 'Full-Time'},
    {value: 'type-1', viewValue: 'Part-Time'},
    {value: 'type-2', viewValue: 'Freelance'},
 
  ];

  workEnvs: WorkEnv[] = [
    {value: 'type-0', viewValue: 'Remote'},
    {value: 'type-1', viewValue: 'Hybrid'},
    {value: 'type-2', viewValue: 'On-site'},
 
  ];

  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 中呈現

您可以異步加載計划。

  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>

在 angular 中使用Change detection 策略

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


constructor(private ref: ChangeDetectorRef) {
 
}


 ngOnInit(): void {

this.service.getPlans()
  .subscribe(response => {
    this.plans = response;
    console.log(response);
    this.ref.detectChanges(); // manually trigger change detection
  });

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM