简体   繁体   English

Angular6:数据未传递给子组件

[英]Angular6: Data is not passed to child component

I am trying to display loading message when the page is loaded. 我正在尝试在加载页面时显示加载消息。 I have created loader component as child component and value is passed from parent. 我已经将loader组件创建为子组件,并且值从父组件传递。 But for some reason loader is not being loaded. 但由于某种原因,装载机没有加载。

I have tried the following code. 我试过以下代码。

I have created a component for loader as below: 我已经为loader创建了一个组件,如下所示:

loader.ts loader.ts

@Input() showLoader: boolean = false;

loader.html loader.html

<div class="modal-backdrop in" [style.display]="showLoader ? 'block' : 'none'">

Now From the component I need to show this loader, I pass on value as below: 现在从我需要显示此加载器的组件,我传递值如下:

html HTML

<app-loader [showLoader]="loaderOn"></app-loader>

ts TS

public loaderOn: boolean = false;

ngOnInit() {
    this.loaderOn = true;
}

The code you shared should work... perhaps there is something missing or an error somewhere in your code; 您共享的代码应该可以工作...也许代码中某处缺少某些内容或出现错误; To make the change more observable, i added a 2 second delay in ngOnInit(); 为了使更改更加可观察,我在ngOnInit()中添加了2秒的延迟;

relevant app.component.ts : 相关的app.component.ts

  loaderOn: boolean = false;

  ngOnInit() {
    setTimeout(() => {
      this.loaderOn = true;
    }, 2000)
  }

relevant app.component.html : 相关的app.component.html

Value sent from the parent: <mark>{{loaderOn}}</mark>
<app-loader [showLoader]="loaderOn"></app-loader>

relevant loader.component.html : 相关的loader.component.html

import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-loader>',
  template: `
    <p>Value received in the child: <mark>{{showLoader}}</mark> </p>

    <div class="modal-backdrop in" [style.display]="showLoader ? 'block' : 'none'">
    ...this is the div which we wanted to style...
    </div>
  `,
  styles: [`*{color:blue}`],
})
export class LoaderComponent {
  @Input() showLoader: boolean = false;

}

complete working stackblitz here 这里完成了stackblitz的工作

Why not just use an ngIf? 为什么不使用ngIf?

loader.html loader.html

<div class="modal-backdrop in">

and hide and show with 并隐藏和显示

<app-loader *ngIf="loaderOn"></app-loader>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM