我对Angular 6(来自1.3和React)非常陌生,在尝试将prop传递给子组件时遇到了一些问题。
这是我的父组件.ts
import { Component, Input, ViewContainerRef, ComponentFactory, ComponentFactoryResolver, ViewChild } from '@angular/core';
import { DashboardButtonComponent } from '../modals/dashboard-button/dashboard-button.component';
@Component({
selector: 'app-admin-dashboard-content',
templateUrl: './admin-dashboard-content.component.html',
styleUrls: ['./admin-dashboard-content.component.css']
})
export class AdminDashboardContentComponent {
title: string;
constructor() {}
ngOnInit(){
this.title="menu #1";
}
}
我试图在构造函数或定义中都初始化标题,但这两种方法都不起作用。我很确定那不是问题。
以下是其.html:
<div class="dashboard-container">
<div class="buttons-container">
<app-dashboard-button [title]="title"></app-dashboard-button>
</div>
</div>
这是子组件。 ts:
import { Component, Input, ChangeDetectorRef, SimpleChanges} from '@angular/core';
@Component({
selector: 'app-dashboard-button',
templateUrl: './dashboard-button.component.html',
styleUrls: ['./dashboard-button.component.css']
})
export class DashboardButtonComponent{
@Input()
title: string;
constructor() {
}
}
html:
<div class="dashboard-button-container">
{{title}}
</div>
我得到的错误如下:
Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'title: undefined'. Current value: 'title: undefined'. It seems like the view has been created after its parent and its children have been dirty checked. Has it been created in a change detection hook ?
关于组件生命周期的工作原理,我可能缺少一些愚蠢的想法,但我认为我需要有人在这里向正确的方向指出。谢谢。