首页 > 解决方案 > 在组件之前渲染数据

问题描述

我想在 html 模板中使用从 HttpClient 服务加载的数据,但看起来数据是在组件之后呈现的,所以我使用指令 ngIf 来解决问题,但它不起作用!有什么帮助吗?

组件.ts :

import { Component, OnInit } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
import { MyserviceService } from '../myservice.service';

@Component({
selector: 'app-forms',
templateUrl: './forms.component.html',
styleUrls: ['./forms.component.css']
})
export class FormsComponent implements OnInit {
ngOnInit() {
this.getBook()

}

constructor(private service : MyserviceService) {
}

Booknames :any

getBook () {
return  this.service.getBookNames().subscribe((data)=> {this.Booknames = data , 
  console.log(this.Booknames)}) ;
}}

组件.html:

<div class="example-container">
  <mat-form-field appearance="fill">
      <mat-label>Enter your name</mat-label>
         <input matInput>
  </mat-form-field>
  <mat-form-field appearance="fill">
    <mat-label>Name-linechart</mat-label>
       <input matInput>
 </mat-form-field>

  <mat-form-field *ngIf="BookNames">
    <mat-label>xAxis-linechart</mat-label>
    <mat-select >
      <mat-option  *ngFor="let book of BookNames" >
        {{book}}
      </mat-option>
    </mat-select>
  </mat-form-field> 

当我运行它时,“xAxis-linechart”字段没有出现!

标签: htmlangulartypescripthttpclient

解决方案


我用 *ngIf="BookNames" 替换 *ngIf="Booknames",我对 *ngFor 做同样的事情,它可以工作!:)


推荐阅读